|
15 | 15 | */
|
16 | 16 | class Solution {
|
17 | 17 | public List<List<Integer>> verticalTraversal(TreeNode root) {
|
18 |
| - Map<Integer, List<TreeCoordinate>> map = new TreeMap<>(); |
19 |
| - Queue<TreeCoordinate> queue = new LinkedList<>(); |
20 |
| - queue.add(new TreeCoordinate(root, 0, 0)); |
| 18 | + Map<Integer, List<NodePair>> map = new HashMap<>(); |
| 19 | + Queue<NodePair> queue = new LinkedList<>(); |
| 20 | + queue.add(new NodePair(0, 0, root)); |
| 21 | + int minColumn = 0; |
| 22 | + int maxColumn = 0; |
21 | 23 | while (!queue.isEmpty()) {
|
22 | 24 | int size = queue.size();
|
23 | 25 | while (size-- > 0) {
|
24 |
| - TreeCoordinate removed = queue.remove(); |
| 26 | + NodePair removed = queue.remove(); |
| 27 | + minColumn = Math.min(minColumn, removed.y); |
| 28 | + maxColumn = Math.max(maxColumn, removed.y); |
25 | 29 | map.computeIfAbsent(removed.y, k -> new ArrayList<>()).add(removed);
|
26 | 30 | if (removed.node.left != null) {
|
27 |
| - queue.add(new TreeCoordinate(removed.node.left, removed.x + 1, removed.y - 1)); |
| 31 | + queue.add(new NodePair(removed.x + 1, removed.y - 1, removed.node.left)); |
28 | 32 | }
|
29 | 33 | if (removed.node.right != null) {
|
30 |
| - queue.add(new TreeCoordinate(removed.node.right, removed.x + 1, removed.y + 1)); |
| 34 | + queue.add(new NodePair(removed.x + 1, removed.y + 1, removed.node.right)); |
31 | 35 | }
|
32 | 36 | }
|
33 | 37 | }
|
34 | 38 | List<List<Integer>> result = new ArrayList<>();
|
35 |
| - for (Integer key : map.keySet()) { |
36 |
| - List<TreeCoordinate> temp = map.get(key); |
37 |
| - Collections.sort(temp, |
38 |
| - Comparator.comparingInt((TreeCoordinate o) -> o.x).thenComparingInt(o -> o.node.val)); |
39 |
| - result.add(temp.stream().map(a -> a.node.val).collect(Collectors.toList())); |
| 39 | + for (int key = minColumn; key <= maxColumn; key++) { |
| 40 | + List<NodePair> list = map.get(key); |
| 41 | + result.add(list.stream() |
| 42 | + .sorted(Comparator.comparingInt((NodePair o) -> o.x).thenComparingInt(o -> o.node.val)) |
| 43 | + .map(np -> np.node.val) |
| 44 | + .collect(Collectors.toList())); |
40 | 45 | }
|
41 | 46 | return result;
|
42 | 47 | }
|
43 | 48 |
|
44 |
| - private static class TreeCoordinate { |
| 49 | + class NodePair { |
| 50 | + int x; |
| 51 | + int y; |
| 52 | + TreeNode node; |
45 | 53 |
|
46 |
| - public TreeNode node; |
47 |
| - public int x; |
48 |
| - public int y; |
49 |
| - |
50 |
| - public TreeCoordinate(TreeNode node, int x, int y) { |
51 |
| - this.node = node; |
| 54 | + public NodePair(int x, int y, TreeNode node) { |
52 | 55 | this.x = x;
|
53 | 56 | this.y = y;
|
| 57 | + this.node = node; |
54 | 58 | }
|
55 | 59 | }
|
56 | 60 | }
|
0 commit comments