Given acompletebinary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
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 2hnodes inclusive at the last level h.
Solution: 对于full tree,node总数为2^height - 1。对于complete tree,所以先在子树找到full tree,直接用高度计算node总数
public int countNodes(TreeNode root) {
if (root == null)
return 0;
TreeNode left = root, right = root;
int height = 0;
while (left != null && right != null) {
left = left.left;
right = right.right;
height++;
}
//此时为full tree
if (left == null && right == null) {
return (1 << height) - 1;
}
//不full时用普通方法
return 1 + countNodes(root.left) + countNodes(root.right);
}