Java Recursive Solution


  • 0
    U
    class Solution {
        private TreeMap<Integer, TreeMap<Integer, List<Integer>>> map = new TreeMap<>();
        private List<List<Integer>> result = new ArrayList<>();
    
        public List<List<Integer>> verticalOrder(TreeNode root) {
            if (root == null) return result;
            helper(root, 0, 0);
            for (Integer key: map.keySet())
            {
                List<Integer> tmpList = new ArrayList<>();
                TreeMap<Integer, List<Integer>> tmpMap = map.get(key);
                for (Integer key2: tmpMap.keySet())
                {
                    for (int i=0; i<tmpMap.get(key2).size(); i++)
                        tmpList.add(tmpMap.get(key2).get(i));
                }
                result.add(tmpList);
            }
            return result;
            
        }
        
        private void helper(TreeNode root, int offset, int depth)
        {
            if (root == null) return;
    
            TreeMap<Integer, List<Integer>> currMap = map.getOrDefault(offset, new TreeMap<Integer, List<Integer>>());
            List<Integer>currList = currMap.getOrDefault(depth, new ArrayList<Integer>());
            currList.add(root.val);
            currMap.put(depth, currList);
            map.put(offset, currMap);
    
            helper(root.left, offset-1, depth+1);
            helper(root.right, offset+1, depth+1);
        }
    }
    

Log in to reply
 

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