我有平凡的解决方案在完整二叉树计算节点的数量:如何在不访问每个节点的情况下统计完整二叉树中的节点数?
public int countNodes(TreeNode root) {
if (root == null) { return 0; }
return 1 + countNodes(root.left) + countNodes(root.right);
}
我明白这一点。但是,我知道这是效率低下的,因为它必须访问每个节点。我还有一个解决方案,我在网上找到:
public int countNodes(TreeNode root) {
if(root==null)
return 0;
int left = getLeftHeight(root)+1;
int right = getRightHeight(root)+1;
if(left==right){
return (2<<(left-1))-1; //having a hard time here
}else{
return countNodes(root.left)+countNodes(root.right)+1;
}
}
public int getLeftHeight(TreeNode n){
if(n==null) return 0;
int height=0;
while(n.left!=null){
height++;
n = n.left;
}
return height;
}
public int getRightHeight(TreeNode n){
if(n==null) return 0;
int height=0;
while(n.right!=null){
height++;
n = n.right;
}
return height;
}
我明白这一点,但我不能完全肯定我理解的条件,如果(leftHeight == rightHeight)。这个怎么用?另外,有人可以解释一下按位操作以及为什么这样工作的原因?我不熟悉按位运算符。也许,如果有人可以用非按位代码替换这个条件,并且翻译那些将会完美的事情!
作者是一个noob。 '2 <<(left-1)'可以简化为'1 << left' – Bohemian