Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 413c86b

Browse filesBrowse files
authored
Create 29 verticalTraversalBT.cpp
1 parent 54b1e0f commit 413c86b
Copy full SHA for 413c86b

File tree

Expand file treeCollapse file tree

1 file changed

+55
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+55
-0
lines changed
+55Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
map<int,vector<pair<int,int>>> mp;
16+
17+
void Traverse_Vertically(TreeNode* root , int curr_x , int curr_y)
18+
{
19+
if(root==NULL)return;
20+
21+
mp[curr_x].push_back({curr_y,root->val});
22+
Traverse_Vertically(root->left , curr_x-1 , curr_y+1);
23+
Traverse_Vertically(root->right , curr_x+1 , curr_y+1);
24+
}
25+
26+
vector<vector<int>> verticalTraversal(TreeNode* root)
27+
{
28+
mp.clear(); // clear the map
29+
30+
vector<int> temp; // temporary vector
31+
32+
Traverse_Vertically(root,0,0); // start vertical traversal from root
33+
34+
vector<vector<int>> ans;
35+
36+
37+
for(auto it:mp)
38+
{
39+
40+
temp.clear();
41+
42+
// sort the pairs {y corrdinates , root->value} in ascending order
43+
sort(it.second.begin(),it.second.end());
44+
45+
// store our current ans in temporary vector
46+
for(auto itr:it.second)
47+
temp.push_back(itr.second);
48+
49+
// store our current traversal
50+
ans.push_back(temp);
51+
}
52+
53+
return ans;
54+
}
55+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.