-
Notifications
You must be signed in to change notification settings - Fork 128
/
Count Complete Tree Nodes.js
69 lines (58 loc) · 1.51 KB
/
Count Complete Tree Nodes.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if (root === null) {
return 0;
}
var tmp = root,
totalDep = 0,
nodeNumsInLastLevel = 0,
node = root,
curDep,
depSplit;
while (tmp) {
tmp = tmp.left;
totalDep++;
}
curDep = 1;
while (curDep < totalDep) {
depSplit = findSplit(node);
if (depSplit + curDep === totalDep) {
nodeNumsInLastLevel += Math.pow(2, depSplit - 1);
node = node.right;
} else {
node = node.left;
}
curDep++;
}
return Math.pow(2, totalDep - 1) + nodeNumsInLastLevel;
};
// find the depth of left most node in right subtree of current node
// binary search in last level
function findSplit(root) {
if (!root || !root.right) {
return 0;
}
var dep = 0,
tmp = root;
tmp = tmp.right;
while(tmp) {
dep++;
tmp = tmp.left;
}
return dep;
}