Given a complete binary tree, count the number of nodes.
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 2 ^ h nodes inclusive at the last level h.
Solution: "Binary Search"
思路:
Time Complexity: T(N) = T(N / 2) + logN (for findHeight) => (logN) ^ 2
Space Complexity: O(logN)递归缓存
Solution Code:
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int root_lheight = getLeftHeight(root);
int left_lheight = root_lheight == 0 ? 0 : root_lheight - 1;
int right_lheight = getLeftHeight(root.right);
int count_ltree, count_rtree;
if(right_lheight == root_lheight - 1) {
// case1: the left subtree is complete
count_ltree = left_lheight == 0 ? 0 : (1 << left_lheight) - 1; // 1 << x == 2 ^ x
count_rtree = countNodes(root.right);
}
else {
// case2: the right subtree is complete (right_lheight == lheight - 2)
count_ltree = countNodes(root.left);
count_rtree = right_lheight == 0 ? 0 : (1 << right_lheight) - 1;
}
int count = 1 + count_ltree + count_rtree; // cur_node + lef_subtree + right_sub_tree
return count;
}
private int getLeftHeight(TreeNode root) {
// length of all the way by left to the end
return root == null ? 0 : 1 + getLeftHeight(root.left);
}
}