How to count the number of nodes in a complete binary tree without visiting each node?

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; //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;
}

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!

+4
1

(leftHight == rightHight) , , , , , perfect (full ) . node , , .

(2<<(left-1))-1 Math.pow(2, left) - 1. 2 :

2<<0 //equals 2 to the power of 1. 2 is shifted zero bits to the left
2<<1 //equals 2 to the power of 2, 2 is shifted 1 bit to the left
2<<2 // equals 2 to the power of 3, 2 is shifted 2 bits to the left
2<<k // equals 2 to the power of k+1, 2 is shifted k bits to the left

, , , h (2**(k+1))-1. 2 (k + 1) 1.

left height+1 . (2<<(left-1))-1 .

+4

Source: https://habr.com/ru/post/1655557/


All Articles