Advertisement
ogv

Untitled

ogv
Nov 8th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. // Runtime: 2 ms, faster than 99.97% of Java online submissions for Vertical Order Traversal of a Binary Tree.
  2. // Memory Usage: 36.3 MB, less than 100.00% of Java online submissions for Vertical Order Traversal of a Binary Tree.
  3. class Solution {
  4.     public List<List<Integer>> verticalTraversal(TreeNode root) {
  5.         Map<Integer, ArrayList<Pair>> map = new HashMap<>();
  6.         traverse(root, 0, 0, map);
  7.        
  8.         List<List<Integer>> result = new LinkedList<>();
  9.        
  10.         ArrayList<Integer> xs = new ArrayList<>(map.keySet());
  11.         Collections.sort(xs);
  12.        
  13.         for (int x: xs) {
  14.             ArrayList<Pair> line = map.get(x);
  15.             Collections.sort(line);
  16.            
  17.             List<Integer> r = new LinkedList<>();            
  18.             for (Pair p: line) r.add(p.val);
  19.  
  20.             result.add(r);            
  21.         }
  22.         return result;
  23.     }
  24.    
  25.     private void traverse(TreeNode root, int x, int y, Map<Integer, ArrayList<Pair>> map) {
  26.         if (root == null) return;
  27.        
  28.         if (!map.containsKey(x)) map.put(x, new ArrayList<Pair>());
  29.         map.get(x).add(new Pair(root.val, y));
  30.        
  31.         traverse(root.left, x-1, y-1, map);
  32.         traverse(root.right, x+1, y-1, map);
  33.     }
  34.    
  35.     class Pair implements Comparable<Pair> {
  36.         public int val;
  37.         public int y;
  38.        
  39.         public Pair(int val, int y) {
  40.             this.val = val;
  41.             this.y = y;
  42.         }
  43.        
  44.         public int compareTo(Pair another) {
  45.             int yDiff = -y + another.y;
  46.             if (yDiff != 0) return yDiff;
  47.             else return val - another.val;
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement