1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { Map<Integer, ArrayList<Pair<Integer, Integer>>> columnTable = new HashMap(); int minColumn = 0, maxColumn = 0;
private void DFS(TreeNode node, Integer row, Integer column) { if (node == null) return;
if (!columnTable.containsKey(column)) { this.columnTable.put(column, new ArrayList<Pair<Integer, Integer>>()); }
this.columnTable.get(column).add(new Pair<Integer, Integer>(row, node.val)); this.minColumn = Math.min(minColumn, column); this.maxColumn = Math.max(maxColumn, column); this.DFS(node.left, row + 1, column - 1); this.DFS(node.right, row + 1, column + 1); }
public List<List<Integer>> verticalTraversal(TreeNode root) { List<List<Integer>> output = new ArrayList(); if (root == null) { return output; }
this.DFS(root, 0, 0);
for (int i = minColumn; i < maxColumn + 1; ++i) { Collections.sort(columnTable.get(i), (p1, p2) -> p1.getKey() != p2.getKey() ? p1.getKey() - p2.getKey() : p1.getValue() - p2.getValue()); List<Integer> sortedColumn = new ArrayList(); for (Pair<Integer, Integer> p : columnTable.get(i)) { sortedColumn.add(p.getValue()); } output.add(sortedColumn); }
return output; } }
|