C++ queue<pair<TreeNode *, int>> 6ms


  • 1
    5
    /**
     * 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) {
            queue<pair<TreeNode*,int>> q;
            vector<vector<int>> res;
            if (root == NULL) return res;
            
            q.push(make_pair(root,0));
            while(!q.empty()){
                pair<TreeNode*,int> currentpair = q.front();
                TreeNode *node = currentpair.first;
                int level = currentpair.second;
                q.pop();
                
                if (res.begin()+level >= res.end()) {
                    vector<int> v={node->val};
                    res.push_back(v);
                }
                else {
                    res[level].push_back(node->val);
                }
                if (node->left != NULL){
                    q.push(make_pair(node->left,level+1));
                }
                if (node->right != NULL){
                    q.push(make_pair(node->right,level+1));
                }
            }
            return res;
        }
    }; 
    
    

Log in to reply
 

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