forked from Google-Developer-Student-Club-CCOEW/Competitive-Programming-2023-GDSC-CUMMINS-X-GDSC-MMCOE
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Vertical Order Traversal of a Binary Tree
Solution to Vertical Order Traversal of a Binary Tree -> issue Google-Developer-Student-Club-CCOEW#98 By Isha Baviskar GitHub ID -> isha0904
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
*/ |