赞
踩
地址: https://labuladong.gitee.io/algo/2/18/31/
2021/12/15
做题反思:
int countNodes(TreeNode root){
if (root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
时间复杂度 O(N):
地址: https://labuladong.gitee.io/algo/2/18/31/
2021/12/15
做题反思:
public int countNodes(TreeNode root) {
int h = 0;
while (root != null) {
root = root.left;
h++;
}
return (int)Math.pow(2, h) - 1;
}
地址: https://leetcode-cn.com/problems/count-complete-tree-nodes/
2021/12/15
做题反思:两个小问题
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
TreeNode l = root, r = root;
int lh = 0, rh = 0;
while (l != null) {
l = l.left;
lh++;
}
while (r != null) {
r = r.right;
rh++;
}
if (rh == lh) {
return (int)Math.pow(2, lh) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
这个算法的时间复杂度是 O(logN*logN)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。