Given the root of a binary Tree, Find its vertical traversal starting from the leftmost level to the rightmost level.
Note: If multiple nodes are at the same horizontal distance from the root and on the same level, they should be printed in the order they appear in a level-order traversal (top-to-bottom, left-to-right).
Here, Horizontal distance is calculated from the root to a specific node by counting how many times we move left or right along the unique path from the root to that node.
The formula for Horizontal distance from the root is given by:
Horizontal Distance = Number of right moves − Number of left moves in the path from the root to that node.
Examples:
Input:
Output: [[4], [2], [1, 5, 6, 11], [3, 8, 9], [7], [10]] Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level
[Naive Approach] - Traversing the Tree for each vertical line
The idea is to traverse the tree once and get the minimum and maximum horizontal distance with respect to root. For the tree shown above example, minimum distance is -2 (for node with value 4) and maximum distance is 3 (For node with value 10).
Once we have maximum and minimum distances from root, we iterate for each vertical line at distance minimum to maximum from root, and for each vertical line traverse the tree and print the nodes which lie on that vertical line.
C++
#include<iostream>#include<vector>#include<queue>#include<algorithm>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Finds the minimum and maximum horizontal distance in the treevoidfindMinMax(Node*node,int&min,int&max,inthd){if(node==nullptr)return;if(hd<min)min=hd;elseif(hd>max)max=hd;// Recur for left and right subtreesfindMinMax(node->left,min,max,hd-1);findMinMax(node->right,min,max,hd+1);}// Collects all nodes at a given vertical distance in level-ordervoidcollectVerticalLine(Node*root,intdist,vector<int>&line){inthd=0;// Create a queue for level order traversalqueue<pair<Node*,int>>q;q.push({root,0});intmn=0,mx=0;while(!q.empty()){pair<Node*,int>curr=q.front();q.pop();Node*node=curr.first;hd=curr.second;if(hd==dist)line.push_back(node->data);if(node->left)q.push({node->left,hd-1});if(node->right)q.push({node->right,hd+1});}}// Returns the vertical order traversal of the treevector<vector<int>>verticalOrder(Node*root){vector<vector<int>>res;intmin=0,max=0;findMinMax(root,min,max,0);for(intline=min;line<=max;line++){vector<int>verticalNodes;// storing nodes for each vertical linescollectVerticalLine(root,line,verticalNodes);res.push_back(verticalNodes);}returnres;}intmain(){// Create binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7// \ \ \ // 8 9 10// /// 11Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->left->right->right=newNode(8);root->right->left->right=newNode(9);root->right->right->right=newNode(10);root->left->right->right->left=newNode(11);vector<vector<int>>res=verticalOrder(root);cout<<"[";for(inti=0;i<res.size();i++){cout<<"[";vector<int>line=res[i];for(intj=0;j<line.size();j++){cout<<line[j];if(j!=line.size()-1)cout<<", ";}cout<<"]";if(i!=res.size()-1)cout<<", ";}cout<<"]";cout<<endl;return0;}
Java
importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{// Finds the minimum and maximum horizontal distance in the treestaticvoidfindMinMax(Nodenode,int[]min,int[]max,inthd){if(node==null)return;if(hd<min[0])min[0]=hd;elseif(hd>max[0])max[0]=hd;// Recur for left and right subtreesfindMinMax(node.left,min,max,hd-1);findMinMax(node.right,min,max,hd+1);}// Collects all nodes at a given vertical distance in level-orderstaticvoidcollectVerticalLine(Noderoot,intdist,ArrayList<Integer>line){inthd=0;// Queue for level-order traversalQueue<ArrayList<Object>>q=newLinkedList<>();ArrayList<Object>first=newArrayList<>();first.add(root);first.add(hd);q.add(first);while(!q.isEmpty()){ArrayList<Object>curr=q.poll();Nodenode=(Node)curr.get(0);hd=(int)curr.get(1);if(hd==dist)line.add(node.data);if(node.left!=null){ArrayList<Object>leftNode=newArrayList<>();leftNode.add(node.left);leftNode.add(hd-1);q.add(leftNode);}if(node.right!=null){ArrayList<Object>rightNode=newArrayList<>();rightNode.add(node.right);rightNode.add(hd+1);q.add(rightNode);}}}// Returns the vertical order traversal of the treestaticArrayList<ArrayList<Integer>>verticalOrder(Noderoot){ArrayList<ArrayList<Integer>>res=newArrayList<>();int[]min={0},max={0};findMinMax(root,min,max,0);for(intline=min[0];line<=max[0];line++){ArrayList<Integer>verticalNodes=newArrayList<>();collectVerticalLine(root,line,verticalNodes);res.add(verticalNodes);}returnres;}publicstaticvoidmain(String[]args){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);ArrayList<ArrayList<Integer>>res=verticalOrder(root);System.out.print("[");for(inti=0;i<res.size();i++){System.out.print("[");ArrayList<Integer>line=res.get(i);for(intj=0;j<line.size();j++){System.out.print(line.get(j));if(j!=line.size()-1)System.out.print(", ");}System.out.print("]");if(i!=res.size()-1)System.out.print(", ");}System.out.println("]");}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Returns the vertical order traversal of the treedeffindMinMax(node,minmax,hd):ifnodeisNone:returnifhd<minmax["min"]:minmax["min"]=hdelifhd>minmax["max"]:minmax["max"]=hd# Recur for left and right subtreesfindMinMax(node.left,minmax,hd-1)findMinMax(node.right,minmax,hd+1)# Collects all nodes at a given vertical distance in level-orderdefcollectVerticalLine(root,dist,line):hd=0# Create a queue for level order traversalq=deque()q.append((root,0))whileq:node,hd=q.popleft()ifhd==dist:line.append(node.data)ifnode.left:q.append((node.left,hd-1))ifnode.right:q.append((node.right,hd+1))# Finds the minimum and maximum horizontal distance in the treedefverticalOrder(root):res=[]minmax={"min":0,"max":0}findMinMax(root,minmax,0)forlineinrange(minmax["min"],minmax["max"]+1):verticalNodes=[]collectVerticalLine(root,line,verticalNodes)res.append(verticalNodes)returnresif__name__=="__main__":# Create binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7# \ \ \# 8 9 10# /# 11root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.left.right.right=Node(8)root.right.left.right=Node(9)root.right.right.right=Node(10)root.left.right.right.left=Node(11)res=verticalOrder(root)print("[",end="")foriinrange(len(res)):print("[",end="")line=res[i]forjinrange(len(line)):print(line[j],end="")ifj!=len(line)-1:print(", ",end="")print("]",end="")ifi!=len(res)-1:print(", ",end="")print("]")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Finds the minimum and maximum horizontal distance in the treestaticvoidfindMinMax(Nodenode,refintmin,refintmax,inthd){if(node==null)return;if(hd<min)min=hd;elseif(hd>max)max=hd;// Recur for left and right subtreesfindMinMax(node.left,refmin,refmax,hd-1);findMinMax(node.right,refmin,refmax,hd+1);}// Collects all nodes at a given vertical distance in level-orderstaticvoidcollectVerticalLine(Noderoot,intdist,List<int>line){inthd=0;// Create a queue for level order traversalQueue<(Node,int)>q=newQueue<(Node,int)>();q.Enqueue((root,0));while(q.Count>0){varcurr=q.Dequeue();Nodenode=curr.Item1;hd=curr.Item2;if(hd==dist)line.Add(node.data);if(node.left!=null)q.Enqueue((node.left,hd-1));if(node.right!=null)q.Enqueue((node.right,hd+1));}}// Returns the vertical order traversal of the treestaticList<List<int>>verticalOrder(Noderoot){List<List<int>>res=newList<List<int>>();intmin=0,max=0;findMinMax(root,refmin,refmax,0);for(intline=min;line<=max;line++){List<int>verticalNodes=newList<int>();collectVerticalLine(root,line,verticalNodes);res.Add(verticalNodes);}returnres;}staticvoidMain(){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);List<List<int>>res=verticalOrder(root);Console.Write("[");for(inti=0;i<res.Count;i++){Console.Write("[");List<int>line=res[i];for(intj=0;j<line.Count;j++){Console.Write(line[j]);if(j!=line.Count-1)Console.Write(", ");}Console.Write("]");if(i!=res.Count-1)Console.Write(", ");}Console.WriteLine("]");}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Finds the minimum and maximum horizontal distance in the treefunctionfindMinMax(node,minmax,hd){if(!node)return;if(hd<minmax.min)minmax.min=hd;elseif(hd>minmax.max)minmax.max=hd;// Recur for left and right subtreesfindMinMax(node.left,minmax,hd-1);findMinMax(node.right,minmax,hd+1);}// Collects all nodes at a given vertical distance in level-orderfunctioncollectVerticalLine(root,dist,line){lethd=0;// Create a queue for level order traversalletq=[];q.push([root,0]);while(q.length>0){let[node,currHd]=q.shift();hd=currHd;if(hd===dist)line.push(node.data);if(node.left)q.push([node.left,hd-1]);if(node.right)q.push([node.right,hd+1]);}}// Returns the vertical order traversal of the treefunctionverticalOrder(root){letres=[];letminmax={min:0,max:0};findMinMax(root,minmax,0);for(letline=minmax.min;line<=minmax.max;line++){letverticalNodes=[];collectVerticalLine(root,line,verticalNodes);res.push(verticalNodes);}returnres;}// Driver Code// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);letres=verticalOrder(root);process.stdout.write("[");for(leti=0;i<res.length;i++){process.stdout.write("[");letline=res[i];for(letj=0;j<line.length;j++){process.stdout.write(line[j].toString());if(j!==line.length-1)process.stdout.write(", ");}process.stdout.write("]");if(i!==res.length-1)process.stdout.write(", ");}console.log("]");
Output
[[4], [2], [1, 5, 6, 11], [3, 8, 9], [7], [10]]
Time Complexity: O(n2), Time complexity of above algorithm is O(w*n) where w is width of Binary Tree and n is number of nodes in Binary Tree. In worst case, the value of w can be n. Auxiliary Space: O(n), due to recursion stack.
[Better Approach] - Using DFS and Sorting - O(n log(n)) Time and O(n) Space
The idea is to traverse the tree using DFS and store the mapping of each horizontal distance to a list of pairs containing the node value and its level. These pairs are required so that nodes can later be printed in the correct order based on their level. Then, we sort the pairs based on their level as the order of nodes in the same level is maintained in DFS, but since DFS explores all nodes in depth before moving to other branches, the order of nodes by level is not naturally preserved.
C++
#include<iostream>#include<vector>#include<queue>#include<algorithm>#include<map>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Performs DFS to map each node to its horizontal distance and levelvoiddfs(Node*root,inthd,intlvl,map<int,vector<pair<int,int>>>&verticalLines){if(root==nullptr)return;// storing node value and levelverticalLines[hd].push_back({root->data,lvl});// Recur for left and right subtreesdfs(root->left,hd-1,lvl+1,verticalLines);dfs(root->right,hd+1,lvl+1,verticalLines);}// Collects all vertical lines after DFS traversal and sorting by levelvector<vector<int>>verticalOrder(Node*root){map<int,vector<pair<int,int>>>verticalLines;dfs(root,0,0,verticalLines);vector<vector<int>>res;for(auto&kv:verticalLines){vector<pair<int,int>>lines=kv.second;// Sorting based on levelstable_sort(lines.begin(),lines.end(),[](auto&a,auto&b){returna.second<b.second;});vector<int>line;for(auto&node:lines){line.push_back(node.first);}res.push_back(line);}returnres;}intmain(){// Create binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7// \ \ \ // 8 9 10// /// 11Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->left->right->right=newNode(8);root->right->left->right=newNode(9);root->right->right->right=newNode(10);root->left->right->right->left=newNode(11);vector<vector<int>>res=verticalOrder(root);cout<<"[";for(inti=0;i<res.size();i++){cout<<"[";vector<int>line=res[i];for(intj=0;j<line.size();j++){cout<<line[j];if(j!=line.size()-1)cout<<", ";}cout<<"]";if(i!=res.size()-1)cout<<", ";}cout<<"]"<<endl;}
Java
importjava.util.List;importjava.util.ArrayList;importjava.util.Map;importjava.util.TreeMap;importjava.util.Collections;importjava.util.Comparator;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{// Performs DFS to map each node to its horizontal distance and levelstaticArrayList<ArrayList<Integer>>verticalOrder(Noderoot){TreeMap<Integer,ArrayList<ArrayList<Integer>>>map=newTreeMap<>();dfs(root,0,0,map);ArrayList<ArrayList<Integer>>res=newArrayList<>();for(inthd:map.keySet()){ArrayList<ArrayList<Integer>>lines=map.get(hd);// Sorting based on level (2nd element in list)Collections.sort(lines,Comparator.comparingInt(a->a.get(1)));ArrayList<Integer>line=newArrayList<>();for(ArrayList<Integer>node:lines){// add only value, not levelline.add(node.get(0));}res.add(line);}returnres;}// Collects all vertical lines after DFS traversal and sorting by levelstaticvoiddfs(Noderoot,inthd,intlvl,TreeMap<Integer,ArrayList<ArrayList<Integer>>>verticalLines){if(root==null)return;ArrayList<ArrayList<Integer>>line=verticalLines.getOrDefault(hd,newArrayList<>());// store node value and level as a small listArrayList<Integer>nodeInfo=newArrayList<>();nodeInfo.add(root.data);nodeInfo.add(lvl);line.add(nodeInfo);verticalLines.put(hd,line);// Recur for left and right subtreesdfs(root.left,hd-1,lvl+1,verticalLines);dfs(root.right,hd+1,lvl+1,verticalLines);}publicstaticvoidmain(String[]args){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);ArrayList<ArrayList<Integer>>res=verticalOrder(root);System.out.print("[");for(inti=0;i<res.size();i++){System.out.print("[");List<Integer>line=res.get(i);for(intj=0;j<line.size();j++){System.out.print(line.get(j));if(j!=line.size()-1)System.out.print(", ");}System.out.print("]");if(i!=res.size()-1)System.out.print(", ");}System.out.println("]");}}
Python
fromcollectionsimportdefaultdict# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Collects all vertical lines after DFS traversal and sorting by leveldefverticalOrder(root):verticalLines=defaultdict(list)dfs(root,0,0,verticalLines)res=[]forhdinsorted(verticalLines.keys()):lines=verticalLines[hd]# Sorting based on levellines.sort(key=lambdax:x[1])line=[]fornodeinlines:line.append(node[0])res.append(line)returnres# Performs DFS to map each node to its horizontal distance and leveldefdfs(root,hd,lvl,verticalLines):ifrootisNone:return# storing node value and levelverticalLines[hd].append((root.data,lvl))# Recur for left and right subtreesdfs(root.left,hd-1,lvl+1,verticalLines)dfs(root.right,hd+1,lvl+1,verticalLines)if__name__=="__main__":# Create binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7# \ \ \# 8 9 10# /# 11root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.left.right.right=Node(8)root.right.left.right=Node(9)root.right.right.right=Node(10)root.left.right.right.left=Node(11)res=verticalOrder(root)print("[",end="")foriinrange(len(res)):print("[",end="")line=res[i]forjinrange(len(line)):print(line[j],end="")ifj!=len(line)-1:print(", ",end="")print("]",end="")ifi!=len(res)-1:print(", ",end="")print("]")
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Collects all vertical lines after DFS traversal and sorting by levelstaticList<List<int>>verticalOrder(Noderoot){SortedDictionary<int,List<int[]>>map=newSortedDictionary<int,List<int[]>>();dfs(root,0,0,map);List<List<int>>res=newList<List<int>>();foreach(inthdinmap.Keys){List<int[]>lines=map[hd];// Sorting based on levellines=lines.OrderBy(a=>a[1]).ToList();List<int>line=newList<int>();foreach(int[]nodeinlines){line.Add(node[0]);}res.Add(line);}returnres;}// Performs DFS to map each node to its horizontal distance and levelstaticvoiddfs(Noderoot,inthd,intlvl,SortedDictionary<int,List<int[]>>verticalLines){if(root==null)return;if(!verticalLines.ContainsKey(hd))verticalLines[hd]=newList<int[]>();// storing node value and levelverticalLines[hd].Add(newint[]{root.data,lvl});// Recur for left and right subtreesdfs(root.left,hd-1,lvl+1,verticalLines);dfs(root.right,hd+1,lvl+1,verticalLines);}staticvoidMain(string[]args){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);List<List<int>>res=verticalOrder(root);Console.Write("[");for(inti=0;i<res.Count;i++){Console.Write("[");List<int>line=res[i];for(intj=0;j<line.Count;j++){Console.Write(line[j]);if(j!=line.Count-1)Console.Write(", ");}Console.Write("]");if(i!=res.Count-1)Console.Write(", ");}Console.WriteLine("]");}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Collects all vertical lines after DFS traversal and sorting by levelfunctionverticalOrder(root){letmap=newMap();dfs(root,0,0,map);letres=[];letkeys=Array.from(map.keys()).sort((a,b)=>a-b);for(lethdofkeys){letlines=map.get(hd);// Sorting based on levellines.sort((a,b)=>a[1]-b[1]);letline=[];for(letnodeoflines){line.push(node[0]);}res.push(line);}returnres;}// Performs DFS to map each node to its horizontal distance and levelfunctiondfs(root,hd,lvl,verticalLines){if(!root)return;letline=verticalLines.get(hd)||[];// storing node value and levelline.push([root.data,lvl]);verticalLines.set(hd,line);// Recur for left and right subtreesdfs(root.left,hd-1,lvl+1,verticalLines);dfs(root.right,hd+1,lvl+1,verticalLines);}// Driver code// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);letres=verticalOrder(root);process.stdout.write("[");for(leti=0;i<res.length;i++){process.stdout.write("[");letline=res[i];for(letj=0;j<line.length;j++){process.stdout.write(line[j].toString());if(j!=line.length-1)process.stdout.write(", ");}process.stdout.write("]");if(i!=res.length-1)process.stdout.write(", ");}console.log("]");
Output
[[4], [2], [1, 5, 6, 11], [3, 8, 9], [7], [10]]
[Expected Approach] - Using BFS - O(n) Time and O(n) Space
In this approach, we are using map to store horizontal distance and nodes having that as horizontal distance from the root. BFS ensures that nodes are traversed in level order traversal. Therefore, we don't need any additional data structure in this approach to maintain level-order traversal.
C++
#include<iostream>#include<vector>#include<queue>#include<algorithm>#include<map>#include<unordered_map>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};vector<vector<int>>verticalOrder(Node*root){// Queue to store nodes and their vertical levels.unordered_map<int,vector<int>>lst;// Queue to store nodes and their vertical levels.queue<pair<Node*,int>>q;q.push({root,0});intmn=0,mx=0;while(!q.empty()){autoc=q.front();mn=min(mn,c.second);mx=max(mx,c.second);q.pop();// adding node to the corresponding vertical level.lst[c.second].push_back(c.first->data);// pushing left child with decreased vertical level.if(c.first->left)q.push({c.first->left,c.second-1});// pushing right child with increased vertical level.if(c.first->right)q.push({c.first->right,c.second+1});}// creating the result vector in vertical order.vector<vector<int>>res;for(inti=mn;i<=mx;i++)res.push_back(lst[i]);returnres;}intmain(){// Create binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7// \ \ \ // 8 9 10// /// 11Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->left->right->right=newNode(8);root->right->left->right=newNode(9);root->right->right->right=newNode(10);root->left->right->right->left=newNode(11);vector<vector<int>>res=verticalOrder(root);cout<<"[";for(inti=0;i<res.size();i++){cout<<"[";vector<int>line=res[i];for(intj=0;j<line.size();j++){cout<<line[j];if(j!=line.size()-1)cout<<", ";}cout<<"]";if(i!=res.size()-1)cout<<", ";}cout<<"]"<<endl;}
Java
importjava.util.List;importjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;importjava.util.Map;importjava.util.HashMap;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classPair<K,V>{privateKkey;privateVvalue;publicPair(Kkey,Vvalue){this.key=key;this.value=value;}publicKgetKey(){returnkey;}publicVgetValue(){returnvalue;}}classGFG{staticArrayList<ArrayList<Integer>>verticalOrder(Noderoot){// Map to store nodes and their vertical levels.Map<Integer,ArrayList<Integer>>lst=newHashMap<>();// Queue to store nodes and their vertical levels.Queue<Pair<Node,Integer>>q=newLinkedList<>();q.offer(newPair<>(root,0));intmn=0,mx=0;while(!q.isEmpty()){Pair<Node,Integer>c=q.poll();mn=Math.min(mn,c.getValue());mx=Math.max(mx,c.getValue());// adding node to the corresponding vertical level.lst.putIfAbsent(c.getValue(),newArrayList<>());lst.get(c.getValue()).add(c.getKey().data);// pushing left child with decreased vertical level.if(c.getKey().left!=null)q.offer(newPair<>(c.getKey().left,c.getValue()-1));// pushing right child with increased vertical level.if(c.getKey().right!=null)q.offer(newPair<>(c.getKey().right,c.getValue()+1));}// creating the result vector in vertical order.ArrayList<ArrayList<Integer>>res=newArrayList<>();for(inti=mn;i<=mx;i++)res.add(lst.get(i));returnres;}publicstaticvoidmain(String[]args){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);ArrayList<ArrayList<Integer>>res=verticalOrder(root);System.out.print("[");for(inti=0;i<res.size();i++){System.out.print("[");List<Integer>line=res.get(i);for(intj=0;j<line.size();j++){System.out.print(line.get(j));if(j!=line.size()-1)System.out.print(", ");}System.out.print("]");if(i!=res.size()-1)System.out.print(", ");}System.out.println("]");}}
Python
fromcollectionsimportdeque,defaultdict# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefverticalOrder(root):ifrootisNone:return[]# Map to store nodes and their vertical levels.lst=defaultdict(list)# Queue to store nodes and their vertical levels.q=deque([(root,0)])mn=0mx=0whileq:node,val=q.popleft()mn=min(mn,val)mx=max(mx,val)# adding node to the corresponding vertical level.lst[val].append(node.data)# pushing left child with decreased vertical level.ifnode.left:q.append((node.left,val-1))# pushing right child with increased vertical level.ifnode.right:q.append((node.right,val+1))# creating the result vector in vertical order.res=[]foriinrange(mn,mx+1):res.append(lst[i])returnresif__name__=="__main__":# Create binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7# \ \ \# 8 9 10# /# 11root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.left.right.right=Node(8)root.right.left.right=Node(9)root.right.right.right=Node(10)root.left.right.right.left=Node(11)res=verticalOrder(root)print("[",end="")foriinrange(len(res)):print("[",end="")line=res[i]forjinrange(len(line)):print(line[j],end="")ifj!=len(line)-1:print(", ",end="")print("]",end="")ifi!=len(res)-1:print(", ",end="")print("]")
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{staticList<List<int>>verticalOrder(Noderoot){List<List<int>>res=newList<List<int>>();if(root==null)returnres;// Map to store nodes and their vertical levels.Dictionary<int,List<int>>lst=newDictionary<int,List<int>>();// Queue to store nodes and their vertical levels.Queue<(Node,int)>q=newQueue<(Node,int)>();q.Enqueue((root,0));intmn=0,mx=0;while(q.Count>0){varcurr=q.Dequeue();Nodenode=curr.Item1;intval=curr.Item2;mn=Math.Min(mn,val);mx=Math.Max(mx,val);// adding node to the corresponding vertical level.if(!lst.ContainsKey(val))lst[val]=newList<int>();lst[val].Add(node.data);// pushing left child with decreased vertical level.if(node.left!=null)q.Enqueue((node.left,val-1));// pushing right child with increased vertical level.if(node.right!=null)q.Enqueue((node.right,val+1));}// creating the result vector in vertical order.for(inti=mn;i<=mx;i++)res.Add(lst[i]);returnres;}staticvoidMain(string[]args){// Create binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);List<List<int>>res=verticalOrder(root);Console.Write("[");for(inti=0;i<res.Count;i++){Console.Write("[");List<int>line=res[i];for(intj=0;j<line.Count;j++){Console.Write(line[j]);if(j!=line.Count-1)Console.Write(", ");}Console.Write("]");if(i!=res.Count-1)Console.Write(", ");}Console.WriteLine("]");}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Custom Queue ImplementationclassQueue{constructor(){this.items=[];this.frontIndex=0;}enqueue(element){this.items.push(element);}dequeue(){if(this.isEmpty())returnnull;constitem=this.items[this.frontIndex];this.frontIndex++;// Optional: Reset array if frontIndex gets largeif(this.frontIndex>1000){this.items=this.items.slice(this.frontIndex);this.frontIndex=0;}returnitem;}isEmpty(){returnthis.frontIndex>=this.items.length;}size(){returnthis.items.length-this.frontIndex;}}functionverticalOrder(root){if(!root)return[];// Map to store nodes and their vertical levelsconstlst=newMap();// Use our custom queueconstq=newQueue();q.enqueue([root,0]);letmn=0,mx=0;while(!q.isEmpty()){const[node,val]=q.dequeue();mn=Math.min(mn,val);mx=Math.max(mx,val);if(!lst.has(val))lst.set(val,[]);lst.get(val).push(node.data);if(node.left)q.enqueue([node.left,val-1]);if(node.right)q.enqueue([node.right,val+1]);}// Build the result in vertical orderconstres=[];for(leti=mn;i<=mx;i++){res.push(lst.get(i));}returnres;}// Driver code// 1// / \// 2 3// / \ / \// 4 5 6 7// \ \ \// 8 9 10// /// 11letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.left.right.right=newNode(8);root.right.left.right=newNode(9);root.right.right.right=newNode(10);root.left.right.right.left=newNode(11);letres=verticalOrder(root);// Display resultprocess.stdout.write("[");for(leti=0;i<res.length;i++){process.stdout.write("[");letline=res[i];for(letj=0;j<line.length;j++){process.stdout.write(line[j].toString());if(j!=line.length-1)process.stdout.write(", ");}process.stdout.write("]");if(i!=res.length-1)process.stdout.write(", ");}console.log("]");