BiruLyu
8/15/2017 - 4:28 PM

314. Binary Tree Vertical Order Traversal(#).java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int min = 0; int max = 0;
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> rst = new ArrayList<List<Integer>>();
if (root == null)
return rst;

recur(root, 0);

queue.offer(root);

ids.offer(-min);

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

while (!queue.isEmpty()) {

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
int id = ids.poll();

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

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

return rst;
}

void recur(TreeNode root, int val) {
if (root == null)
return;

min = Math.min(val, min);
max = Math.max(val, max);

recur(root.left, val - 1);
recur(root.right, val + 1);
}
}``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int min = 0;
private int max = 0;
private void helper(TreeNode root, int level, Map<Integer, List<Integer>> map) {
if (root == null) return;
min = Math.min(level, min);
max = Math.max(level, max);
map.putIfAbsent(level, new ArrayList<>());
helper(root.left, level - 1, map);
helper(root.right, level + 1, map);
}
public List<List<Integer>> verticalOrder(TreeNode root) {
Map<Integer, List<Integer>> map = new HashMap<>();
helper(root, 0, map);
List<List<Integer>> res = new ArrayList<>();
for (int i = min; i <= max; i++) {
}
return res;
}
}

/*
[3,9,8,4,0,1,7,null,null,null,2,5]
[[4],[9,5],[3,0,1],[2,8],[7]]
[[4],[9,5],[3,0,1],[8,2],[7]]
*/``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Node {
TreeNode root;
int level;
public Node(TreeNode root, int level) {
this.root = root;
this.level = level;
}
}
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>> map = new HashMap<>();
q.offer(new Node(root, 0));
int min = 0;
while (!q.isEmpty()) {
Node cur = q.poll();
map.putIfAbsent(cur.level, new ArrayList<>());
if (cur.root.left != null) {
q.offer(new Node(cur.root.left, cur.level - 1));
min = Math.min(min, cur.level - 1);
}
if (cur.root.right != null) {
q.offer(new Node(cur.root.right, cur.level + 1));
//min = Math.min(min, cur.level + 1);
}
}
while (map.containsKey(min)) {