share my java solution!


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        class Col_Node{
            TreeNode node;
            int col;
            
            Col_Node(TreeNode node,int col){
                this.node=node;
                this.col=col;
            }
        }
        public List<List<Integer>> verticalOrder(TreeNode root) {
               List<List<Integer>> res=new ArrayList<>();
               Queue<Col_Node> queue=new LinkedList<>();
               Map<Integer,ArrayList<Integer>> map=new HashMap<>();
               
               if(root==null) return res;
               
               queue.add(new Col_Node(root,0));
               
               int leftcol=0;
               int rightcol=0;
               while(!queue.isEmpty()){
                   
                   int size=queue.size();
                   while(size--!=0){
                       Col_Node temp=queue.poll();
                       int col=temp.col;
                       if(!map.containsKey(col)){
                           map.put(col,new ArrayList<>());
                       }
                       map.get(col).add(temp.node.val);
                       
                       leftcol=Math.min(leftcol,col);
                       rightcol=Math.max(rightcol,col);
                       
                       if(temp.node.left!=null){
                           queue.offer(new Col_Node(temp.node.left,col-1));
                       }
                       if(temp.node.right!=null){
                           queue.offer(new Col_Node(temp.node.right,col+1));
                       }
                   }
               }
               
               
               for(int i=leftcol;i<=rightcol;i++){
                   res.add(map.get(i));
               }
               
               return res;
        }
        
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.