-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count Complete Tree Nodes.java
39 lines (34 loc) · 1.07 KB
/
Count Complete Tree Nodes.java
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
/*
Given a complete binary tree, count the number of nodes.
Link: https://leetcode.com/problems/count-complete-tree-nodes/
Example: None
Solution: None
Source: https://leetcode.com/discuss/81091/simple-java-solution-o-log-n-2-108-ms-with-explanation
*/
/**
* 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) {
return root == null ? 0 : findLastIndex(root, 1);
}
private int lHeight(TreeNode node, int count) {
return node == null ? count - 1 : lHeight(node.left, count + 1);
}
private int findLastIndex(TreeNode node, int currIndex) {
if (node.left == null && node.right == null) {
return currIndex;
}
if (lHeight(node.left, 1) == lHeight(node.right, 1)) {
return findLastIndex(node.right, currIndex * 2 + 1);
} else {
return findLastIndex(node.left, currIndex * 2);
}
}
}