Skip to content

Commit 4ecb0b9

Browse files
authored
Create vertical-order-traversal-of-a-binary-tree.cpp
1 parent f2c4678 commit 4ecb0b9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
using Lookup = map<int, map<int, multiset<int>>>;
16+
17+
vector<vector<int>> verticalTraversal(TreeNode* root) {
18+
Lookup lookup;
19+
dfs(root, &lookup, 0, 0);
20+
vector<vector<int>> result;
21+
for (const auto& kvp1 : lookup) {
22+
vector<int> report;
23+
for (const auto& kvp2 : kvp1.second) {
24+
for (const auto& x : kvp2.second) {
25+
report.emplace_back(x);
26+
}
27+
}
28+
result.emplace_back(move(report));
29+
}
30+
return result;
31+
}
32+
33+
private:
34+
void dfs(TreeNode *root, Lookup *lookup, int x, int y){
35+
if (!root) {
36+
return;
37+
}
38+
(*lookup)[x][y].emplace(root->val);
39+
dfs(root->left, lookup, x - 1, y + 1);
40+
dfs(root->right, lookup, x + 1, y + 1);
41+
}
42+
};

0 commit comments

Comments
 (0)