Given 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.
Horizontal Distance = Number of right moves − Number of left moves in the path from the root to that node.
Examples:Â Â
Input: root = [1, 2, 3, 4, 5, 6, 7, N, N, N, 8, N, 9, N, 10, 11, N]
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.
Input: root = [1, 2, 3, 4, 5, N, 6]
Output: [[4], [2], [1, 5], [3], [6]] Explanation: From left to right the vertical order will be [[4], [2], [1, 5], [3], [6]]
[Naive Approach] Traversing the Tree for Each Vertical Line - O(n ^ 2) Time and O(n) Space
The idea is to first traverse the tree to find the minimum and maximum horizontal distances (HD) from the root. In the example tree, the minimum HD is -2 (node 4) and the maximum HD is 3 (node 10).
Working of Approach:
Find the minimum and maximum horizontal distances (HD) from the root.
Iterate through each vertical line from the minimum HD to the maximum HD.
Perform a level-order traversal (BFS) and collect nodes whose HD matches the current vertical line.
Store the collected nodes in the result in left-to-right vertical order.
C++
#include<algorithm>#include<iostream>#include<queue>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=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]]
[Better Approach] DFS and Sorting – O(n log n) Time and O(n) Space
The idea is to traverse the tree using Depth-First Search (DFS) and store each node's value and level according to its horizontal distance (HD) from the root.
This groups the nodes belonging to the same vertical line.
Since DFS may visit deeper nodes before shallower nodes, we sort the nodes in each vertical line by their levels to maintain the correct order.
Finally, we collect the node values from left to right to obtain the vertical order traversal.
Working of Approach:
Traverse the tree using DFS and track the horizontal distance and level of each node.
Sort the nodes in each vertical line by level using a stable sort, preserving left-to-right order when levels are equal.
Collect the node values from left to right to obtain the result.
C++
#include<algorithm>#include<iostream>#include<map>#include<queue>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=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.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;importjava.util.Map;importjava.util.TreeMap;// 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] BFS – O(n) Time and O(n) Space
The idea is to traverse the tree using Breadth-First Search (BFS) and store each node's value in a map based on its horizontal distance (HD) from the root.
The horizontal distance decreases by 1 for the left child and increases by 1 for the right child.
Since BFS visits nodes level by level, the nodes are stored in the correct order within each vertical line without requiring additional sorting.
Finally, we collect the nodes from the minimum to the maximum horizontal distance to obtain the vertical order traversal.
Working of Approach:
Initialize a queue with the root node and its horizontal distance as 0.
Traverse the tree using BFS and store each node's value at its corresponding horizontal distance.
Update the minimum and maximum horizontal distances during traversal.
Collect the nodes from the minimum to the maximum horizontal distance to obtain the result.
C++
#include<algorithm>#include<iostream>#include<map>#include<queue>#include<unordered_map>#include<vector>usingnamespacestd;classNode{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.*;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}publicclassGFG{publicstaticArrayList<ArrayList<Integer>>verticalOrder(Noderoot){// Map to store nodes at each vertical level.Map<Integer,ArrayList<Integer>>lst=newHashMap<>();if(root==null)returnnewArrayList<>();// Queue to store nodes and their vertical levels.Queue<AbstractMap.SimpleEntry<Node,Integer>>q=newLinkedList<>();q.add(newAbstractMap.SimpleEntry<>(root,0));intmn=0,mx=0;while(!q.isEmpty()){AbstractMap.SimpleEntry<Node,Integer>c=q.poll();Nodenode=c.getKey();inthd=c.getValue();mn=Math.min(mn,hd);mx=Math.max(mx,hd);// Adding node to the corresponding vertical// level.lst.computeIfAbsent(hd,k->newArrayList<>()).add(node.data);// Pushing left child with decreased vertical// level.if(node.left!=null)q.add(newAbstractMap.SimpleEntry<>(node.left,hd-1));// Pushing right child with increased vertical// level.if(node.right!=null)q.add(newAbstractMap.SimpleEntry<>(node.right,hd+1));}// Creating the result 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("[");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,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("]");