Given a complete binary tree, count the number of nodes.
解题思路:
直接暴力求解超时,注意到一个完全二叉树,它的任何子树,要么是一个满二叉树,要么是一个完全二叉树。通过求一个二叉树最左的深度,最右的深度,来判断是不是满二叉树,如果不是满二叉树,则递归求解,如果是则套用公式(2 << 深度) - 1。
public class Solution {
public int countNodes(TreeNode root) {
if(root == null)
return 0;
int left = getLeft(root.left);
int right = getRight(root.right);
if(left == right){
return (2<<left)-1;
}
else{
return countNodes(root.left)+countNodes(root.right)+1;
}
}
public int getLeft(TreeNode root){
int left = 0;
while(root != null){
root = root.left;
left++;
}
return left;
}
public int getRight(TreeNode root){
int right = 0;
while(root != null){
root = root.right;
right++;
}
return right;
}
}