|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
4 | 4 |
|
5 |
| -import java.util.List; |
6 |
| -import java.util.ArrayList; |
7 |
| -import java.util.PriorityQueue; |
8 |
| -import java.util.TreeMap; |
| 5 | +import java.util.*; |
9 | 6 |
|
10 | 7 | public class _987 {
|
11 | 8 | public static class Solution1 {
|
@@ -42,4 +39,64 @@ private void dfs(TreeNode root, int x, int y, TreeMap<Integer, TreeMap<Integer,
|
42 | 39 | dfs(root.right, x + 1, y + 1, map);
|
43 | 40 | }
|
44 | 41 | }
|
| 42 | + |
| 43 | + public static class Solution2 { |
| 44 | + |
| 45 | + /** |
| 46 | + * My completely original solution on 6/13/2024. |
| 47 | + */ |
| 48 | + public List<List<Integer>> verticalTraversal(TreeNode root) { |
| 49 | + TreeMap<Integer, List<NodeWithCoords>> map = new TreeMap<>(); |
| 50 | + Queue<NodeWithCoords> q = new LinkedList<>(); |
| 51 | + q.offer(new NodeWithCoords(root, 0, 0)); |
| 52 | + while (!q.isEmpty()) { |
| 53 | + int size = q.size(); |
| 54 | + for (int i = 0; i < size; i++) { |
| 55 | + NodeWithCoords curr = q.poll(); |
| 56 | + int col = curr.col; |
| 57 | + int row = curr.row; |
| 58 | + List<NodeWithCoords> list = map.getOrDefault(col, new ArrayList<>()); |
| 59 | + list.add(curr); |
| 60 | + map.put(col, list); |
| 61 | + if (curr.node.left != null) { |
| 62 | + q.offer(new NodeWithCoords(curr.node.left, row + 1, col - 1)); |
| 63 | + } |
| 64 | + if (curr.node.right != null) { |
| 65 | + q.offer(new NodeWithCoords(curr.node.right, row + 1, col + 1)); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + List<List<Integer>> result = new ArrayList<>(); |
| 70 | + for (Integer key : map.keySet()) { |
| 71 | + List<NodeWithCoords> list = map.get(key); |
| 72 | + Collections.sort(list, (a, b) -> { |
| 73 | + if (a.row != b.row) { |
| 74 | + return a.row - b.row; |
| 75 | + } else if (a.col != b.col) { |
| 76 | + return a.col - b.col; |
| 77 | + } else { |
| 78 | + return a.node.val - b.node.val; |
| 79 | + } |
| 80 | + }); |
| 81 | + List<Integer> intList = new ArrayList<>(); |
| 82 | + for (NodeWithCoords nodeWithCoords : list) { |
| 83 | + intList.add(nodeWithCoords.node.val); |
| 84 | + } |
| 85 | + result.add(intList); |
| 86 | + } |
| 87 | + return result; |
| 88 | + } |
| 89 | + |
| 90 | + class NodeWithCoords { |
| 91 | + TreeNode node; |
| 92 | + int row; |
| 93 | + int col; |
| 94 | + |
| 95 | + public NodeWithCoords(TreeNode node, int row, int col) { |
| 96 | + this.node = node; |
| 97 | + this.row = row; |
| 98 | + this.col = col; |
| 99 | + } |
| 100 | + } |
| 101 | + } |
45 | 102 | }
|
0 commit comments