-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Vertical Order Traversal.java
107 lines (94 loc) · 2.67 KB
/
Binary Tree Vertical Order Traversal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
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.
Link: http://leetcode.com/problems/binary-tree-vertical-order-traversal/
Example:
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]
]
Solution: None
Source: http://www.cnblogs.com/yrbbest/p/5065457.html
*/
/**
* 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;
}
Queue<TreeColumnNode> queue = new LinkedList<>();
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)) {
map.get(node.col).add(node.treeNode.val);
} 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++) {
res.add(map.get(i));
}
return res;
}
}