二叉樹的垂直遍歷

題目:二叉樹的垂直遍歷

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;
}
發佈了200 篇原創文章 · 獲贊 740 · 訪問量 69萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章