-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
64 lines (50 loc) · 1.28 KB
/
Copy pathsolution.cpp
File metadata and controls
64 lines (50 loc) · 1.28 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
*/
class Solution
{
public:
vector<vector<int>> verticalOrder(Node *root)
{
vector<vector<int>> result;
if (!root)
return result;
// Map to store nodes grouped by horizontal distance
map<int, vector<int>> mp;
// Queue for BFS traversal
queue<pair<Node *, int>> q;
// Start with root at horizontal distance 0
q.push({root, 0});
while (!q.empty())
{
auto front = q.front();
q.pop();
Node *node = front.first;
int hd = front.second;
// Store node value in map
mp[hd].push_back(node->data);
// Push left child with hd - 1
if (node->left)
q.push({node->left, hd - 1});
// Push right child with hd + 1
if (node->right)
q.push({node->right, hd + 1});
}
// Build final result from map
for (auto &it : mp)
{
result.push_back(it.second);
}
return result;
}
};