BFS with 3ms


  • 0
    L

    BFS with curCount recorded the number of nodes in the current level, and use nextCount to count the number of nodes in the next level.

        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> arr;
            if(root == NULL) return arr;
            int curCount = 0, nextCount = 0;
            vector<int> tmpArr;
            queue<TreeNode*> q;
            curCount = 1;
            q.push(root);
            while(!q.empty())
            {
                TreeNode* node = q.front();
                q.pop();
                curCount --;
                tmpArr.push_back(node->val);
                if(node->left)
                {
                    q.push(node->left);
                    nextCount ++;
                }
                if(node->right)
                {
                    q.push(node->right);
                    nextCount ++;
                }
                if(curCount == 0)
                {
                    arr.push_back(tmpArr);
                    tmpArr.clear();
                    curCount = nextCount;
                    nextCount = 0;
                }
            }
            return arr;
        }
    

Log in to reply
 

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