public static int pow2(int x){
if(x==1)
return 1;
else{
/**
* 必须用一个数来保存左移的结果
* 否则not a statement
* 移x位,等于乘以x个2
* 2 《《 x
* 这样就是2^x+1次方了
*/
int num = 0;
num = 1 << x ;
return num-1;
}
}
/**
*
* 对于一个节点node,计算它最左端的节点到node的深度为leftDepth,计算它最右端的节点到node的深度是rightDepth;
如果leftDepth和rightDepth相等,那么以node为根节点的树是一棵满二叉树,此时以node为根节点的树的节点个数是pow(2,leftDepth)-1;
如果leftDepth和rightDepth不相等,递归求解node的左子树的节点数和右子树的节点数。
*/
public int countNodes(TreeNode root) {
if(root==null)
return 0;
int leftDepth = 0;
int rightDepth = 0;
/**
* 统计左边子树高度
*/
for(TreeNode node = root;node!=null;node=node.left)
leftDepth++;
for(TreeNode node = root;node!=null;node=node.right)
rightDepth++;
if(leftDepth==rightDepth){
return pow2(leftDepth);
} else{
return 1+countNodes(root.left)+countNodes(root.right);
}
}