C++ iterative solution


  • 2
    L

    use bit operation instead of pow. The bit operation will speed up our program.

     int countNodes(TreeNode* root) {
        if (!root) return 0;
        if (!root->left && !root->right) return 1;
        int d = 1; // the depth of the tree
        int leaves = 0;
        int dl, dr;
        while (true){
            if (!root->right){
                leaves++;
                break;
            }
            dl = depth(root->left);
            dr = depth(root->right);
            d = max(d, dl+1);
            // like binary search
            if (dl == dr){
                leaves += 1<<dl;
                root = root->right;
            }
            else{
                root = root->left;
            }
            
        }
        return (1<<d)-1 + leaves;
    }
    int depth(TreeNode* root){
        int d = -1;
        while (root){
            d+= 1;
            root = root->left;
        }
        return d;
    }

  • 0
    X

    very nice solution


  • 0
    S

    Great approach.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.