C++ solution using two queues, it is well understood(3 ms)


  • 0
    W

    With two queues:

    • que1 is a queue of the nodes in the current level.
    • que2 is a queue of the nodes in the next level.
    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode* root) {
            vector<vector<int> > res_vec;
            vector<int> cur_vec;
            queue<TreeNode*> que1, que2;
            if (!root) return res_vec;
            que1.push(root);
            while(!que1.empty()) {
                while(!que1.empty()) {
                    TreeNode* t = que1.front();
                    if (t->right) que2.push(t->right);
                    if (t->left) que2.push(t->left);
                    cur_vec.insert(cur_vec.begin(),t->val);
                    que1.pop();
                }
                res_vec.push_back(cur_vec);
                cur_vec.resize(0);
                queue<TreeNode*> tmp_que = que2; que2 = que1; que1 = tmp_que;
            }
            return res_vec;
        }
    };
    

Log in to reply
 

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