- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountCompleteTreeNodes.java
More file actions
Latest commit
66 lines (53 loc) · 1.86 KB
/
Copy pathCountCompleteTreeNodes.java
File metadata and controls
66 lines (53 loc) · 1.86 KB
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
publicclassCountCompleteTreeNodes {
/**
*
Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
*/
publicintcountNodes(TreeNoderoot) {
if (root == null) return0;
intlevel = 0;
TreeNodecur = root;
while (cur != null) {
level++;
cur = cur.left;
}
inttotalNodesBeforeLastLevel = (1 << (level - 1)) - 1;
returntotalNodesBeforeLastLevel + nodesOfLastLevel(root, level);
}
publicintnodesOfLastLevel(TreeNoderoot, intlevel) {
if (root == null) return0;
if (level == 1 && root != null) return1;
if (level == 2) {
if (root.right != null) return2;
if (root.left != null) return1;
return0;
}
TreeNodemidNode = root.left;
for (inti = 0; i < level - 2; i++) {
midNode = midNode.right;
}
if (midNode == null) returnnodesOfLastLevel(root.left, level - 1);
return (1 << (level - 2)) + nodesOfLastLevel(root.right, level - 1);
}
publicstaticvoidmain(String[] args) {
CountCompleteTreeNodesa = newCountCompleteTreeNodes();
TreeNodeb = newTreeNode(1);
b.left = newTreeNode(2);
b.right = newTreeNode(3);
b.left.left = newTreeNode(4);
b.left.right = newTreeNode(5);
b.right.left = newTreeNode(6);
System.out.println(a.countNodes(b));
}
}