c++ solution easy to understand


  • 0
    Q
    /**
     * 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:
        int max_layer;
        int min_layer = INT_MAX;
        struct node{
                int val;
                int layer;
                node *left;
                node *right;
                node(int v, int l): val(v), layer(l), left(NULL),right(NULL) {};
        };
        vector<vector<int>> verticalOrder(TreeNode* root) {
            
            if(root == nullptr)
                return vector<vector<int>> {};
            
            int layer = 1;
            TreeNode* cur = root;
            
            node *nr = build(root,layer);
            
            vector<vector<int>> res(max_layer-min_layer + 1, vector<int>());
            queue<node*> q;
            q.push(nr);
            while(!q.empty()){
                node *t = q.front();
                q.pop();
                int l;
                if(min_layer != 1)
                    l = t->layer + abs(min_layer);
                else
                    l = t->layer - 1;
                res[l].push_back(t->val);
                if(t->left)
                    q.push(t->left);
                if(t->right)
                    q.push(t->right);
            }
            
            return res;
            
        }
        
        node* build(TreeNode* root, int layer){
            if(root == nullptr)
                return nullptr;
            max_layer = max(max_layer, layer);
            min_layer = min(min_layer, layer);
            node* nr = new node(root->val,layer);
            nr->left = build(root->left,layer-1);
            nr->right = build(root->right, layer+1);
            return nr;
            
        }
    };
    

Log in to reply
 

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