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.
Examples 1:
Input: [3,9,20,null,null,15,7]
3
/\
/ \
9 20
/\
/ \
15 7
Output:
[
[9],
[3,15],
[20],
[7]
]
Examples 2:
Input: [3,9,8,4,0,1,7]
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
Output:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Examples 3:
Input: [3,9,8,4,0,1,7,null,null,null,2,5]
(0's right child is 2 and 1's left child is 5)
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
Output:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
這道題讓我們豎直遍歷二叉樹,並把每一列存入一個二維數組,看題目中給的第一個例子,3和 15 屬於同一列,3在前,第二個例子中,3,5,2 在同一列,3在前,5和2緊隨其后,那么隱約的可以感覺到好像是一種層序遍歷的前后順序,如何來確定列的順序呢,這里可以把根節點給個序號0,然后開始層序遍歷,凡是左子節點則序號減1,右子節點序號加1,這樣可以通過序號來把相同列的節點值放到一起,用一個 TreeMap 來建立序號和其對應的節點值的映射,用 TreeMap 的另一個好處是其自動排序功能可以讓列從左到右,由於層序遍歷需要用到 queue,此時 queue 里不能只存節點,而是要存序號和節點組成的 pair 對兒,這樣每次取出就可以操作序號,而且排入隊中的節點也賦上其正確的序號,代碼如下:
class Solution { public: vector<vector<int>> verticalOrder(TreeNode* root) { vector<vector<int>> res; if (!root) return res; map<int, vector<int>> m; queue<pair<int, TreeNode*>> 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; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/314
類似題目:
Binary Tree Level Order Traversal
參考資料:
https://leetcode.com/problems/binary-tree-vertical-order-traversal/