没看完全二叉树,直接使用一般的遍历交了几发,结果当然是超时了。根据完全二叉树的特点,表示能够按照顺序进行排序的情况,因此我们首先要判断左右的高度是不是相等的,假如相等的话就可以直接使用公式进行计算,否则就要进行一个递推。
public int countNodes(TreeNode root) {
int result=0;
if(root==null){
return result;
}
int left=getLeft(root)+1;
int right=getRight(root)+1;
if(left==right){
result=2<<(left-1)-1;
}else {
result=countNodes(root.left)+countNodes(root.right)+1;
}
return result;
}
public int getLeft(TreeNode root){
int result=0;
while(root.left!=null){
result++;
root=root.left;
}
}
public int getRight(TreeNode root){
int result=0;
if(root.right!=null){
result++;
root=root.right;
}
}