# Binary Tree Vertical Order Traversal

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:

1. 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]
]
``````

2.Given binary tree [3,9,8,4,0,1,7]

``````     3
/\
/  \
9   8
/\  /\
/  \/  \
4  01   7
``````

return its vertical order traversal as:

``````[
[4],
[9],
[3,0,1],
[8],
[7]
]
``````

3.Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)

``````     3
/\
/  \
9   8
/\  /\
/  \/  \
4  01   7
/\
/  \
5   2
``````

return its vertical order traversal as:

``````[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     public var val: Int
*     public var left: TreeNode?
*     public var right: TreeNode?
*     public init(_ val: Int) {
*         self.val = val
*         self.left = nil
*         self.right = nil
*     }
* }
*/
class Solution {
func verticalOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else {
return []
}

var result: [[Int]] = []
var map: [Int: [Int]] = [:]

var queue: [TreeNode] = []
queue.append(root)

var levels: [Int] = []
levels.append(0)

var maxLevel = Int.min, minLevel = Int.max

while queue.count > 0 {
let node = queue.removeFirst()
let level = levels.removeFirst()
maxLevel = max(maxLevel, level)
minLevel = min(minLevel, level)

if var nodes = map[level] {
nodes.append(node.val)
map[level] = nodes
} else {
map[level] = [node.val]
}

if let left = node.left {
queue.append(left)
levels.append(level - 1)
}

if let right = node.right {
queue.append(right)
levels.append(level + 1)
}
}

for l in minLevel...maxLevel {
if let nodes = map[l] {
result.append(nodes)
}
}

return result
}
}
``````
``````/**
* 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>> result = new ArrayList<>();
if (root == null) {
return result;
}

Map<Integer, List<Integer>> map = new HashMap<>();

queue.offer(root);

level.offer(0);

int minLevel = 0, maxLevel = 0;

while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int l = level.poll();

minLevel = Math.min(minLevel, l);
maxLevel = Math.max(maxLevel, l);

if (map.containsKey(l)) {
} else {
List<Integer> list = new ArrayList<>();
map.put(l, list);
}

if (node.left != null) {
queue.offer(node.left);
level.offer(l - 1);
}

if (node.right != null) {
queue.offer(node.right);
level.offer(l + 1);
}
}

for (int i = minLevel; i <= maxLevel; i++) {
if (map.containsKey(i)) {