跳转至

二叉树的垂序遍历⚓︎

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 {
private:
    vector<tuple<int, int, int>> nodes;

    void dfs(TreeNode* root, int row, int column) {
        if (!root) return;

        nodes.emplace_back(column, row, root->val);

        dfs(root->left, row + 1, column - 1);
        dfs(root->right, row + 1, column + 1);
    }

public:
    vector<vector<int>> verticalTraversal(TreeNode* root) {
        dfs(root, 0, 0);

        sort(nodes.begin(), nodes.end());

        vector<vector<int>> res;
        int prevColumn = INT_MIN;

        for (const auto& [column, _, value] : nodes) {
            if (column != prevColumn) {
                prevColumn = column;
                res.emplace_back();
            }
            res.back().emplace_back(value);
        }

        return res;
    }
};