LeetCode 314. 二叉树的垂直遍历**(double)

具体思路:

没想到bfs层序,直接按照map存储列来遍历,真牛皮啊。。。

具体代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(!root)
            return ret;
        map<int,vector<int>>mp;
        queue<pair<TreeNode*,int>>q;
        q.push({root,0});
        while(!q.empty()){
            int size=q.size();
            while(size!=0){
                size--;
                auto pa=q.front();
                q.pop();
                mp[pa.second].push_back(pa.first->val);
                if(pa.first->left)
                    q.push({pa.first->left,pa.second-1});
                if(pa.first->right)
                    q.push({pa.first->right,pa.second+1});
            }
        }
        for(auto it=mp.begin();it!=mp.end();it++){
            ret.push_back(it->second);
        }
        return ret;
    }
};

你可能感兴趣的:(LeetCode刷题记录,leetcode)