简体   繁体   中英

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

I have the trivial solution to counting the number of nodes in a complete binary tree:

public int countNodes(TreeNode root) {
    if (root == null) { return 0; }
    return 1 + countNodes(root.left) + countNodes(root.right);
}

I understand this. However, I am aware that it is inefficient as it has to visit each node. I have another solution that I found online:

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 completely sure I understand the condition if (leftHeight == rightHeight). How does this work? Also, could someone please explain the bitwise operation and the reason for why this works? Im not familiar with bitwise operators. Perhaps, if someone could replace that condition with none-bitwise code, and translate whats going on that would be perfect!

The condition (leftHight == rightHight) in a subtree of a tree that we know is a complete tree means that the current subtree is a perfect (full) binary tree. In a perfect binary tree every node has exactly two children except the leaf nodes which have no children.

The bitwise statement (2<<(left-1))-1 is the same as Math.pow(2, left) - 1 . In general powers of 2 can be calculated as below:

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

Now if you look at the link above you'll see that the number of nodes in a perfect binary tree of height h is (2**(k+1))-1 . That is 2 to the power of (k+1) minus 1.

In the above code left is height+1 notice the plus one in the code. There fore (2<<(left-1))-1 is really calculating the the number nodes in that perfect binary tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM