Simple C++ solution, 8ms


  • 0
    C
        vector<vector<int>> verticalOrder(TreeNode* root) 
        {
            vector<vector<int>> res;
            if(!root)   return res;
            
            map<int, vector<int>> M;
            queue<pair<TreeNode*, int>> Q;
            Q.push({root, 0});
            
            while(!Q.empty())
            {
                auto node = Q.front().first;
                int x = Q.front().second;
                Q.pop();
                
                M[x].push_back(node->val);
                if(node->left)
                    Q.push({node->left, x-1});
                if(node->right)
                    Q.push({node->right, x+1});
            }
            for(auto m : M)
                res.push_back(m.second);
            
            return res;
        }

Log in to reply
 

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