Skip to content

Commit 089078d

Browse files
authored
Update Vertical Order Traversal Of a Binary Tree.java
1 parent 9da58f4 commit 089078d

File tree

1 file changed

+22
-18
lines changed

1 file changed

+22
-18
lines changed

Hard/Vertical Order Traversal Of a Binary Tree.java

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,42 +15,46 @@
1515
*/
1616
class Solution {
1717
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;
2123
while (!queue.isEmpty()) {
2224
int size = queue.size();
2325
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);
2529
map.computeIfAbsent(removed.y, k -> new ArrayList<>()).add(removed);
2630
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));
2832
}
2933
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));
3135
}
3236
}
3337
}
3438
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()));
4045
}
4146
return result;
4247
}
4348

44-
private static class TreeCoordinate {
49+
class NodePair {
50+
int x;
51+
int y;
52+
TreeNode node;
4553

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) {
5255
this.x = x;
5356
this.y = y;
57+
this.node = node;
5458
}
5559
}
5660
}

0 commit comments

Comments
 (0)