完全二叉树
1. 普通二叉树的遍历,统计节点个数
public int countNodes(TreeNode root){
if (root == null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
2. 满二叉树的节点总数
public int countNodes(TreeNode root){
int h = 0;
while (root != null){
root = root.left;
h++;
}
return (int)Math.pow(2,h) - 1;
}
3. 完全二叉树的节点总数
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,hl) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}