4ms Java solution


  • 0
    T
    class NewNode{
            TreeNode node;
            int index;
            NewNode( TreeNode node,int index){
                this.index = index;
                this.node = node;
            }
        }
        public List<List<Integer>> verticalOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<>();
            Queue<NewNode> queue = new LinkedList<>();
            if(root == null) return list;
            queue.add(new NewNode(root,0));
            int n = 0;
            while(!queue.isEmpty()){
                NewNode curNewNode = queue.poll();
                TreeNode cur = curNewNode.node;
                if(cur == null) continue;
                else if(curNewNode.index + n < 0){
                    n++;
                    list.add(0,new ArrayList<Integer>());
                }
                else if(curNewNode.index + n >= list.size()) list.add(new ArrayList<Integer>());
                list.get(curNewNode.index + n).add(new Integer(cur.val));
                queue.add(new NewNode(cur.left,curNewNode.index - 1));
                queue.add(new NewNode(cur.right,curNewNode.index + 1));
            }
            return list;
        }
    

Log in to reply
 

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