Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:
Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its vertical order traversal as:

[
[9],
[3,15],
[20],
[7]
]

Given binary tree [3,9,20,4,5,2,7],

    _3_
/ \
9 20
/ \ / \
4 5 2 7

return its vertical order traversal as:

[
[4],
[9],
[3,5,2],
[20],
[7]
]
分析:
For root, col = 0. The col of root's left child is root.col - 1, and the col of root's right child is root.col + 1.
public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
} Map<Integer, List<Integer>> col_nodes = new HashMap<>();
Map<TreeNode, Integer> node_col = new HashMap<>();
node_col.put(root, ); Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int min = ;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int col = node_col.get(node);
if (!col_nodes.containsKey(col)) {
col_nodes.put(col, new ArrayList<>());
}
col_nodes.get(col).add(node.val); if (node.left != null) {
queue.add(node.left);
node_col.put(node.left, col - );
}
if (node.right != null) {
queue.add(node.right);
node_col.put(node.right, col + );
}
min = Math.min(min, col);
}
while (col_nodes.containsKey(min)) {
res.add(col_nodes.get(min++));
}
return res;
}
}
 public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
Map<Integer, List<Integer>> col_nodes = new HashMap<>();
helper(root, , col_nodes);
return getColNodes(col_nodes);
} private List<List<Integer>> getColNodes(Map<Integer, List<Integer>> col_nodes) {
List<List<Integer>> res = new ArrayList<>();
Integer min = col_nodes.keySet().stream().min((i, j) -> i.compareTo(j)).get();
while (col_nodes.containsKey(min)) {
res.add(col_nodes.get(min));
min++;
}
return res;
} private void helper(TreeNode root, int col, Map<Integer, List<Integer>> col_nodes) {
if (root == null) return;
List<Integer> nodes = col_nodes.getOrDefault(col, new ArrayList<>());
nodes.add(root.value);
col_nodes.put(col, nodes);
helper(root.left, col - , col_nodes);
helper(root.right, col + , col_nodes);
}
}

Reference:

https://discuss.leetcode.com/topic/31115/using-hashmap-bfs-java-solution

http://www.cnblogs.com/yrbbest/p/5065457.html

http://www.programcreek.com/2014/04/leetcode-binary-tree-vertical-order-traversal-java/

上一篇:C# 中的委托和事件详解


下一篇:转载 -- C# 中的委托和事件