算法:
如果左子树高度和右子树高度相等,说明左子树是满二叉树,节点个数为
如果左子树高度和右子树高度不相等,说明右子树是满二叉树,节点个数为
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
if(left == right){
return (int)Math.pow(2, left) + countNodes(root.right);
}
else{
return (int)Math.pow(2, right) + countNodes(root.left);
}
}
public int getHeight(TreeNode root){
if(root == null){
return 0;
}
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
return (int)Math.max(leftHeight, rightHeight) + 1;
}
}