题目:
Given a complete binary 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.
求一棵完全二叉树的节点个数。
题解:
一开始,我用层次遍历来做,直接超时。然后考虑采用递归,就是分别对左右子树进行递归计算,最后就是左右子树的个数+1(root)。但是这里又有一个小技巧,就是首先先求左右子树的高度,如果这两个高度一样,那么就是满二叉树,那么我们就可以直接根据满二叉树的定义来求树的所有节点,node = 2 ^ h -1个节点。但是如果直接用java的Math.pow(double a,double b),那么就会超时,所以在求2的n次幂的时候,考虑用<<左移运算符。
Code:
public static int countNodes(TreeNode root)
{
if(root == null)
return 0;
TreeNode lt = root;
TreeNode rt = root;
int leftdepth = 0;
int rightdepth = 0;
while(lt != null)
{
leftdepth++;
lt = lt.left;
}
while(rt != null)
{
rightdepth++;
rt = rt.right;
}
if(leftdepth == rightdepth)
return (1<<leftdepth) - 1;
else
return countNodes(root.left) + countNodes(root.right) + 1;
}