Advertisement
ogv

Untitled

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