/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
Map<Integer, List<Integer>> map = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.offer(root);
queue.offer(0);
int min = 0, max = 0;
while (!queue.isEmpty()) {
TreeNode node = nodeQueue.poll();
int column = queue.poll();
if (map.containsKey(column)) {
List<Integer> list = map.get(column);
list.add(node.val);
} else {
List<Integer> list = new LinkedList<>();
list.add(node.val);
map.put(column, list);
}
if (node.left != null) {
nodeQueue.offer(node.left);
queue.offer(column - 1);
if (min > column - 1) {
min = column - 1;
}
}
if (node.right != null) {
nodeQueue.offer(node.right);
queue.offer(column + 1);
if (max < column + 1) {
max = column + 1;
}
}
}
for (int i = min; i <= max; i++) {
res.add(map.get(i));
}
return res;
}
}
Binary Tree Vertical Order Traversal
本文介绍了一种二叉树的垂直遍历算法,通过使用队列和哈希映射来实现节点按列顺序的收集。该算法首先将根节点放入队列,并为其分配初始列编号,然后依次处理队列中的每个节点,将其值添加到对应列的列表中。同时,对于每个节点的左右子节点,更新其列编号并加入队列。最终,按照列编号的顺序整理输出结果。
摘要由CSDN通过智能技术生成