-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path222_CountCompleteTreeNodes.java
More file actions
34 lines (31 loc) · 1.02 KB
/
222_CountCompleteTreeNodes.java
File metadata and controls
34 lines (31 loc) · 1.02 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
// 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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int hl = 0, hr = 0;
TreeNode l = root;
TreeNode r = root;
while(l != null) {
hl++;
l = l.left;
}
while(r != null) {
hr++;
r = r.right;
}
if(hr == hl) return (1 << hr) - 1;//位移更省时
// if(hr == hl) return (int)Math.pow(2, hr) - 1;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}