c++ solution using one queue without null mark


  • 0
    K
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            if(!root) return res;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty())
            {
                int num = q.size();
                vector<int> level;
                for(int i = 0; i < num; ++i)
                {  
                    auto top = q.front();
                    q.pop();
                    if(top->left) q.push(top->left);
                    if(top->right) q.push(top->right);
                    level.push_back(top->val);
                }
                res.push_back(level);
            }
            
            return res;
            
        }
    };

Log in to reply
 

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