满二叉树和完全二叉树
完全二叉树:每一层都是紧凑靠左
完全二叉树:每层都是满的
思路
普通二叉树
public int countNodes(TreeNode root){
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
满二叉树
public int countNodes(TreeNode root){
int h=0;
//计算二叉树高度
while(root != null){
root = root.left;
h++;
}
//节点数为2**h-1
return (int)Math.pow(2,h) - 1;
}
完全二叉树
public int countNodes(TreeNode root){
TreeNode l = root,r = root;
//记录左右子树的高度
int hl = 0,hr = 0;
while(l!=null){
l=l.left;
hl++;
}
while(r!=null){
r=r.right;
hr++;
}
//如果左右子树高度相同,则为满二叉树
if(hl == hr) return (int)Math.pow(2,h) - 1;
//否则为普通二叉树
return 1 + countNodes(root.left) + countNodes(root.right);
}