Leetcode-Day15

从零开始Leetcode – Day 15

Count Complete Tree Nodes

https://leetcode.com/problems/count-complete-tree-nodes/
注意直接递归会超时, log(N)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var countNodes = function(root) {
if(root ===null){
return 0;
}
var l = leftDepth(root);
var r = rightDepth(root);

if(l =r){
return (Math.pow(2, l)-1);
} else{
return 1 + countNodes(root.left) + countNodes(root.right);
}

};

var leftDepth = function(root){
var h = 0;
while(root !==null){
h++;
root = root.left

}
return h;
};

var rightDepth = function(root){
var h = 0;
while(root !==null){
h++;
root = root.right;
}
return h;
};