Given a complete binary tree, count the number of nodes.
Note: In a complete binary tree, every level except possibly the last, is completely filled, and all nodes in 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; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int h = treeHeight(root);
int left = 1;
int right = (int)Math.pow(2, h) - 1;
// Binary search on last layer to see if exists
while (left <= right) {
int mid = left + (right - left) / 2;
if (nodeExists(mid, root, h)) left = mid + 1;
else right = mid - 1;
}
return left + (int)Math.pow(2, h) - 1;
}
// Computes the tree height
private static int treeHeight(TreeNode root) {
int height = 0;
while (root.left != null) {
root = root.left;
height ++;
}
return height;
}
// Verifies if index node exits in tree
private static boolean nodeExists(int index, TreeNode root, int height) {
int left = 0;
int right = (int)Math.pow(2, height) - 1;
// go down the tree d times,
for (int i = 0; i < height; i++) {
int mid = left + (right - left) / 2;
// each time making corresponding move to reach index
if (index <= mid) {
root = root.left;
right = mid;
}
else {
root = root.right;
left = mid + 1;
}
}
return root != null;
}
}