From 110fb4f8460fc95555ae6d0294a25e1ebe58a552 Mon Sep 17 00:00:00 2001 From: Kathyayani Date: Mon, 7 Nov 2022 00:20:11 +0530 Subject: [PATCH] Vertical_Traversal --- algorithms/CPlusPlus/Trees/Vertical_Order.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/Vertical_Order.cpp diff --git a/algorithms/CPlusPlus/Trees/Vertical_Order.cpp b/algorithms/CPlusPlus/Trees/Vertical_Order.cpp new file mode 100644 index 00000000..e68befdb --- /dev/null +++ b/algorithms/CPlusPlus/Trees/Vertical_Order.cpp @@ -0,0 +1,43 @@ +class Solution +{ + public: + //Function to find the vertical order traversal of Binary Tree. + vector verticalOrder(Node *root) + { + //Your code here + list>l;//queue having hd and node + map>mp;// a vertical level mapped to ele in that level + vectorans;//ans vector + if(!root)return ans; + l.push_back({0,root}); + while(!l.empty()){ + + pairp=l.front(); + //frst is hd and second is node + mp[p.first].push_back(p.second->data);//map data to the vertical level it belongs to + if(p.second->left)l.push_back({p.first-1,p.second->left});//hd=current-1 for left + if(p.second->right)l.push_back({p.first+1,p.second->right});//hd=current +1 for right + l.pop_front(); + } + // now map has elements acc to level + // make a vector each for a level + //push that vector to ans vector + + /* map looks like this + frst snd + begin: (-1)-> [9] + begin+1: (0)-> [3,15] + begin+2: (1)-> [20] + begin+3: (2)-> [7] */ + for(auto it=mp.begin();it!=mp.end();it++){ + pair>q=*it; + int size=q.second.size(); + vectorlevel; + for(int i=0;i