跳转至

二叉树的垂直遍历⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

/**
 * 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>> res;
        if (!root) return res;

        map<int, vector<int>> columnTable;
        queue<pair<TreeNode*, int>> que;
        que.emplace(root, 0);

        while (!que.empty()) {
            auto p = que.front();
            que.pop();

            columnTable[p.second].emplace_back(p.first->val);

            if (p.first->left) que.emplace(p.first->left, p.second - 1);
            if (p.first->right) que.emplace(p.first->right, p.second + 1);
        }

        for (auto& col : columnTable) {
            res.emplace_back(col.second);
        }
        return res;
    }
};