[LeetCode] Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal

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

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
/**
* 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, multimap<int, int>> m;
void build(TreeNode* node, int order = 0, int depth = 0) {
if(!node) return;
m[order].insert({depth, node->val});
build(node->left, order - 1, depth + 1);
build(node->right, order + 1, depth + 1);
}
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
build(root);
vector<vector<int>> res;
transform(m.begin(), m.end(), back_inserter(res), [](auto const& e) {
vector<int> _res;
transform(e.second.begin(), e.second.end(), back_inserter(_res), [](auto const& _e) {return _e.second;});
return _res; });
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/26/PS/LeetCode/binary-tree-vertical-order-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.