Simple c++ solution using two queues / 9 ms


  • 0
    P
    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode *root) {
            vector<vector<int> >  result;
            if (!root) return result;
            queue<TreeNode*> main_q;
            queue<TreeNode*> aux_q;
            main_q.push(root);
            result.push_back(vector<int>(1,root->val));
            while(!main_q.empty()) {
                TreeNode* n = main_q.front();
                if (n->left) aux_q.push(n->left);
                if (n->right) aux_q.push(n->right);
                main_q.pop();
                if (main_q.empty()) {
                    vector<int> cur_vec;
                    while(!aux_q.empty()) {
                        TreeNode* m = aux_q.front();
                        cur_vec.push_back(m->val);
                        main_q.push(m);
                        aux_q.pop();
                    }
                    if (cur_vec.size() > 0) result.push_back(cur_vec);
                }
            }
            return result;
        }
    };

Log in to reply
 

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