forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0987.cpp
More file actions
executable file
·31 lines (27 loc) · 762 Bytes
/
LC0987.cpp
File metadata and controls
executable file
·31 lines (27 loc) · 762 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
Time: O(n • log³ n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, map<int, set<int>, greater<int>>> mp;
function<void(int, int, TreeNode*)> dfs = [&](int x, int y, TreeNode* root) {
if (!root)
return;
mp[x][y].insert(root->val);
dfs(x - 1, y - 1, root->left);
dfs(x + 1, y - 1, root->right);
};
dfs(0, 0, root);
vector<vector<int>> order;
for (auto& [x, m]: mp) {
order.push_back(vector<int>());
for (auto& [y, v]: m)
order.back().insert(order.back().end(), v.begin(), v.end());
}
return order;
}
};