二叉树的垂直遍历

题目:二叉树的垂直遍历

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;
    queueint, 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;
}

你可能感兴趣的:(笔试面试编程题,剑指Offer,笔试面试,编程题)