# 314. 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]
]```

Time Complexity – O(n)，  Space Complexity – O(n)

```/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private class TreeColumnNode{
public TreeNode treeNode;
int col;
public TreeColumnNode(TreeNode node, int col) {
this.treeNode = node;
this.col = col;
}
}

public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) {
return res;
}
Map<Integer, List<Integer>> map = new HashMap<>();
queue.offer(new TreeColumnNode(root, 0));
int curLevel = 1;
int nextLevel = 0;
int min = 0;
int max = 0;

while(!queue.isEmpty()) {
TreeColumnNode node = queue.poll();
if(map.containsKey(node.col)) {
} else {
map.put(node.col, new ArrayList<Integer>(Arrays.asList(node.treeNode.val)));
}
curLevel--;

if(node.treeNode.left != null) {
queue.offer(new TreeColumnNode(node.treeNode.left, node.col - 1));
nextLevel++;
min = Math.min(node.col - 1, min);
}
if(node.treeNode.right != null) {
queue.offer(new TreeColumnNode(node.treeNode.right, node.col + 1));
nextLevel++;
max = Math.max(node.col + 1, max);
}
if(curLevel == 0) {
curLevel = nextLevel;
nextLevel = 0;
}
}

for(int i = min; i <= max; i++) {
}

return res;
}
}```

Reference:

https://leetcode.com/discuss/75054/5ms-java-clean-solution

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

https://leetcode.com/discuss/74022/hashmap-bfs-solution-in-java

https://leetcode.com/discuss/73893/java-level-order-traversal-solution

Print the Binary Tree in Vertical Order Path.

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

http://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/

原文作者：YRB
原文地址: https://www.cnblogs.com/yrbbest/p/5065457.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。