My bfs solution with C++ (8ms)


  • 0
    Y
    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode *root) {
            vector<vector<int> > vv;
            if ( !root )
                return vv;
            int cur = 1;
            vector<int> v;
            queue<TreeNode*> q;
            TreeNode* p;
            q.push(root);
            v.push_back(root->val);
            while ( cur )
            {
                vv.push_back(v);
                v.clear();
                int child = 0;
                for ( int i=0; i<cur; ++i )
                {
                    p = q.front();
                    if ( p->left )
                    {
                        q.push(p->left);
                        v.push_back(p->left->val);
                        child++;
                    }
                    if ( p->right )
                    {
                        q.push(p->right);
                        v.push_back(p->right->val);
                        child++;
                    }
                    q.pop();
                }
                cur = child;
            }
            return vv;
        }
    };

Log in to reply
 

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