-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Complete Tree Nodes.java
More file actions
35 lines (33 loc) · 1.02 KB
/
Count Complete Tree Nodes.java
File metadata and controls
35 lines (33 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
35
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// O(log(n)*log(n)), iterative and recursive
public int countNodes(TreeNode root) {
if(root == null) return 0;
// get left height and right height
int height = 0;
TreeNode ln = root, rn = root;
// right hit null faster
while(rn != null) {
ln = ln.left;
rn = rn.right;
height++;
}
// if complete, 2^h-1
if(ln == null) return (1<<height) - 1;
// for this recursion, at least one subtree would be complete and terminate
return 1 + countNodes(root.left) + countNodes(root.right);
}
// // O(n)
// public int countNodes(TreeNode root) {
// if(root == null) return 0;
// return 1 + countNodes(root.left) + countNodes(root.right);
// }
}