题目描述
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
题目链接
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
方法思路
TreeMap 是一个有序的key-value集合,它是通过红黑树实现的。
TreeMap 继承于AbstractMap,所以它是一个Map,即一个key-value集合。
优先队列的作用是能保证每次取出的元素都是队列中权值最小的(Java的优先队列每次取最小元素,C++的优先队列每次取最大元素)。
Java中PriorityQueue通过二叉小顶堆实现,可以用一棵完全二叉树表示。
//Runtime: 3 ms, faster than 98.30%
//Memory Usage: 37.5 MB, less than 22.46%
public List<List<Integer>> verticalTraversal(TreeNode root) {
TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map = new TreeMap<>();
dfs(root, 0, 0, map);
List<List<Integer>> list = new ArrayList<>();
for (TreeMap<Integer, PriorityQueue<Integer>> ys : map.values()) {
list.add(new ArrayList<>());
for (PriorityQueue<Integer> nodes : ys.values()) {
while (!nodes.isEmpty()) {
list.get(list.size() - 1).add(nodes.poll());
}
}
}
return list;
}
private void dfs(TreeNode root, int x, int y, TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map) {
if (root == null) {
return;
}
if (!map.containsKey(x)) {
map.put(x, new TreeMap<>());
}
if (!map.get(x).containsKey(y)) {
map.get(x).put(y, new PriorityQueue<>());
}
map.get(x).get(y).offer(root.val);
dfs(root.left, x - 1, y + 1, map);
dfs(root.right, x + 1, y + 1, map);
}
}