Pseudocode
Created a class that will hold the node and its horizontal height
Using BFS, so create a queue and inserted the first node having a horizontal height of 0
Popped the element from the queue, if the horizontal height doesn't exist in the map then created an entry for it
get the ArrayList of horizontal height and add the value of the node to it
check for the left and right child, if they are not null then add them to the queue
class Solution { class Node{ TreeNode key; int h; Node(TreeNode key,int h){ this.key=key; this.h=h; } } public List<List<Integer>> verticalTraversal(TreeNode root) { if(root==null) return null; TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>(); Queue<Node> q=new LinkedList<>(); q.add(new Node(root,0)); while(!q.isEmpty()){ Node tmp=q.poll(); if(!map.containsKey(tmp.h)) map.put(tmp.h,new ArrayList<Integer>()); map.get(tmp.h).add(tmp.key.val); if(tmp.key.left!=null) q.add(new Node(tmp.key.left,tmp.h-1)); if(tmp.key.right!=null) q.add(new Node(tmp.key.right,tmp.h+1)); } List<List<Integer>> ans=new ArrayList<>(); for(ArrayList<Integer> al:map.values()){ ans.add(al); } return ans; }
}
Problem Failing for input