二叉树的垂直遍历

题目:二叉树的垂直遍历

Given a binary tree, return the vertical order traversal of its nodes’ values. (ie, 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.

例子:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its vertical order traversal as:

[
  [9],
  [3,15],
  [20],
  [7]
]

Given binary tree [3,9,20,4,5,2,7],

    _3_
   /   \
  9    20
 / \   / \
4   5 2   7

return its vertical order traversal as:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

思路标签:

  • 数据结构:队列
  • 每个节点加列标签

解答:

  • 以根结点的标签为0作为基础,每个节点的左子结点-1,右子节点+1,相同标签的都存在一个vector中;
  • 利用map来映射相同标签的vector;
  • 利用队列来对每个节点进行处理,同时入队的为绑定标签的节点,用pair来绑定。
struct BinaryTree {
    int val;
    BinaryTree *left;
    BinaryTree *right;
    BinaryTree(int value) :
        val(value), left(nullptr), right(nullptr) { }
};

vector<vector<int> > verticalOrder(BinaryTree *root) {
    vector<vector<int> > res;
    if (root == nullptr) 
        return res;

    map<int, vector<int>> m;
    queue<pair<int, BinaryTree*>> q;
    q.push({ 0, root });
    while (!q.empty()) {
        auto a = q.front();
        q.pop();
        m[a.first].push_back(a.second->val);
        if (a.second->left)
            q.push({a.first-1, a.second->left});
        if (a.second->right)
            q.push({a.first+1, a.second->right});
    }
    for (auto a : m) {
        res.push_back(a.second);
    }

    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值