Java solution with 2 vectors


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    import java.util.Vector;
    public class Solution {
        Vector<List<Integer>> negativeLists = new  Vector<List<Integer>>();
        Vector<List<Integer>> positiveLists = new  Vector<List<Integer>>();
        
        public List<List<Integer>> verticalOrder(TreeNode root) {
            preOrderTraversal(root);
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            for(int i = negativeLists.size()-1; i > 0; i--){
                if(negativeLists.get(i) != null){
                    result.add(negativeLists.get(i));
                }
            }
            for(int i = 0; i < positiveLists.size(); i++) {
                if(positiveLists.get(i) != null){
                    result.add(positiveLists.get(i));
                }
            }
            return result;
        }
        
        private static class IndexedNode {
            public TreeNode node;
            public int index;
            public IndexedNode(){ }
            public IndexedNode(TreeNode n, int i) {
                node = n;
                index = i;
            }
        }
        
        private void preOrderTraversal(TreeNode node) {
            if(node == null) {
                return;
            }
            Queue<IndexedNode> queue = new LinkedList<IndexedNode>();
            queue.add(new IndexedNode(node, 0));
            while(!queue.isEmpty()) {
                IndexedNode n = queue.remove();
                Vector<List<Integer>> vecLists = n.index < 0 ? negativeLists : positiveLists;
                int i = Math.max(n.index, 0 - n.index);
                while(vecLists.size() < i + 1){
                    vecLists.add(null);
                }
                if(vecLists.get(i) == null) {
                    vecLists.set(i, new ArrayList<Integer>());
                }
                vecLists.get(i).add(n.node.val);
                
                if(n.node.left != null){
                    queue.add(new IndexedNode(n.node.left, n.index-1));
                }
                if(n.node.right != null){
                    queue.add(new IndexedNode(n.node.right, n.index+1));
                }
            }
        }
    }
    

Log in to reply
 

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