T(n) = T(n/2) + logn = O(logn*logn)
public class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
// count the height for the left most leaf and right most leaf
// if threr are equal, then it's perfect binary tree
// nodes would be
TreeNode tmp_left = root.left, tmp_right = root.right;
int left_het = 1, right_het = 1;
while (tmp_left != null) {
tmp_left = tmp_left.left;
left_het++;
}
while (tmp_right != null) {
tmp_right = tmp_right.right;
right_het++;
}
if (left_het == right_het)
// (int) Math.pow(2, left_het) will TLE
return (1 << left_het) - 1;
// divide and conquer
return countNodes(root.left) + countNodes(root.right) + 1;
}
}