• 欢迎光临~

[Oracle] LeetCode 314 Binary Tree Vertical Order Traversal

开发技术 开发技术 2022-10-27 次浏览

Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Solution

我们用 (map)(map)(vector) 来储存每个 (row, col) 的节点值,因为对于左节点等价于: (row+1, col-1).

那么我们对树进行 (DFS), 然后再对 (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 {
private:
    vector<vector<int>> ans;
    map<int, map<int, vector<int>> >mp;
    
    void dfs(TreeNode* rt, int row,int col){
        if(!rt) return;
        mp[col][row].push_back(rt->val);
        dfs(rt->left, row+1, col-1);
        dfs(rt->right, row+1, col+1);
    }
    
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        dfs(root, 0,0);
        for(auto ele:mp){
            vector<int> tmp;
            for(auto m2:ele.second){
                for(auto ele2:m2.second)tmp.push_back(ele2);
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};
程序员灯塔
转载请注明原文链接:[Oracle] LeetCode 314 Binary Tree Vertical Order Traversal
喜欢 (0)
违法和不良信息举报电话:022-22558618 举报邮箱:dljd@tidljd.com