Not able to get the right approach. Both level order Traversal and recursive size function fails


  • 0
    T
     int countNodes(TreeNode* root) {
            int count=0;
            if(root==NULL)
                return 0;
            queue<TreeNode*>Q;
            Q.push(root);
            while(!Q.empty()){
                TreeNode* temp=Q.front();
                Q.pop();
                count++;
                if(temp->left)
                    Q.push(temp->left);
                if(temp->right)
                    Q.push(temp->right);
            }
            return count;
        }
    
    /*recursive function
    int countNode(TreeNode* root){
         if(root==NULL)
               return 0;
         else return countNode(root->left)+1+countNode(root->right);
    }*/

  • 1

    How many dots do you see here?

    . . . . . . .
    . . . . . . .
    . . . . . . .
    . . . . . . .
    . . . . . . .
    . . . . . . .
    

    More important question: Did you count them one by one? Or did you take advantage of the structure? Same thing with counting those tree nodes. Take advantage of the tree's completeness.


Log in to reply
 

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