Description
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:
Input: [3,9,20,null,null,15,7]
3
/
/
9 20
/
/
15 7
Output:
[
[9],
[3,15],
[20],
[7]
]
Examples 2:
Input: [3,9,8,4,0,1,7]
3
/\
/
9 8
/\ /
/ /
4 01 7
Output:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Examples 3:
Input: [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
Output:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
Solution
给一棵二叉树,返回这棵二叉树按照从左到右的列的结果。
We use BFS to solve this problem. We use a map from int to ArrayList<Integer> to denote which col has what values. Using two queues to denotes node we should go next in BFS and its column number.
Using a while loop to perform BFS, Every new col will create a new Array list in colsvalue and then stores the value of this node into it. Then for the left child and right child of the tree node in queue’s poll(), assign corresponding col value to them and add them into queue. We use min and max int to store the range of col. After the BFS, store the value via min and max into res.
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null){
return res;
}
Map<Integer, ArrayList<Integer>> colsValue = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> colsKey = new LinkedList<>();
int min = 0, max = 0;
queue.add(root);
colsKey.add(0);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
int col = colsKey.poll();
if (!colsValue.containsKey(col)){
colsValue.put(col, new ArrayList<>());
}
colsValue.get(col).add(node.val);
if (node.left != null){
queue.add(node.left);
colsKey.add(col - 1);
min = Math.min(min, col - 1);
}
if (node.right != null){
queue.add(node.right);
colsKey.add(col + 1);
max = Math.max(max, col + 1);
}
}
for (int i = min; i <= max; i++){
res.add(colsValue.get(i));
}
return res;
}
}
Time Complexity: O()
Space Complexity: O()