I have a trivial solution for counting the number of nodes in a binary binary tree complete :
public int countNodes(TreeNode root) {
if (root == null) { return 0; }
return 1 + countNodes(root.left) + countNodes(root.right);
}
I understand it. However, I know that it is inefficient as it must visit every node. I have another solution that I found on the Internet:
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;
}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;
}
I understand this, but I'm not quite sure that I understand the if condition (leftHeight == rightHeight). How it works? Also, can someone explain the explanation of the bitwise operation and the reason why this works? I am not familiar with bitwise operators. Perhaps if someone can replace this condition with non-bitwise code and translate what happens, it will be great!