[LeetCode] Vertical Order Traversal of a Binary Tree

987. Vertical Order Traversal of a Binary Tree

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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 {
map<int, map<int, vector<int>>> order;
void travel(TreeNode* node, int r, int c) {
if(!node) return;
order[c][r].push_back(node->val);
travel(node->left, r + 1, c - 1);
travel(node->right, r + 1, c + 1);
}
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<vector<int>> res;
travel(root, 0, 0);
for(auto [c, rowMap]: order) {
vector<int> ans;
for(auto [r, vec] : rowMap) {
sort(vec.begin(),vec.end());
ans.insert(ans.end(), vec.begin(), vec.end());
}
res.push_back(ans);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/23/PS/LeetCode/vertical-order-traversal-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.