-
Notifications
You must be signed in to change notification settings - Fork 69
/
VerticalOrderTraversalOfBT.txt
65 lines (49 loc) Β· 1.98 KB
/
VerticalOrderTraversalOfBT.txt
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
65
//Solution to Issue #98 -> Vertical Order Traversal of Binary Tree
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
// Answer vector to store the vertical traversal results.
vector<vector<int>> ans;
// Queue to perform a level-order traversal of the binary tree.
queue<pair<TreeNode*, pair<int, int>>> q;
// Traverse from the root node
q.push({root, {0, 0}});
// Map to store nodes based on their column, row, and values.
map<int, map<int, multiset<int>>> mp;
// Level-order traversal of the binary tree.
while (!q.empty()) {
// Get the front element of the queue.
auto front = q.front();
q.pop();
TreeNode* &node = front.first;
auto &coordinate = front.second;
int &row = coordinate.first;
int &col = coordinate.second;
// Current node
mp[col][row].insert(node->val);
// for Left child
if (node->left)
q.push({node->left, {row + 1, col - 1}});
// for right child
if (node->right)
q.push({node->right, {row + 1, col + 1}});
}
// Map to construct the final result vector.
for (auto it : mp) {
auto &colmap = it.second;
vector<int> vline;
for (auto mpit : colmap) {
auto &mset = mpit.second;
vline.insert(vline.end(), mset.begin(), mset.end());
}
// Adding the values from the current column to the answer vector.
ans.push_back(vline);
}
// Return the vertical traversal result.
return ans;
}
};
/*
By Isha Baviskar ([email protected])
ID -> isha0904
*/