651 · 二叉树垂直遍历
描述
给定二叉树,返回其节点值的垂直遍历顺序。 (即逐列从上到下)。
如果两个节点在同一行和同一列中,则顺序应 从左到右。
样例
样例1
输入: {3,9,20,#,#,15,7}
输出: [[9],[3,15],[20],[7]]
解释:
3
/
/
9 20
/
/
15 7
样例2
输入: {3,9,8,4,0,1,7}
输出:[[4],[9],[3,0,1],[8],[7]]
解释:
3
/
/
9 8
/\ /
/ /
4 01 7
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of tree
* @return: the vertical order traversal
*/
public List<List<Integer>> verticalOrder(TreeNode root) {
// write your code here
List<List<Integer>> ans = new ArrayList<>() ;
if(root == null){
return null ;
}
int col_min = 0 ;
int col_max = 0 ;
Map<Integer , List<Integer>> col = new HashMap<>() ;
Queue<Integer> q1 = new LinkedList<>() ;
Queue<TreeNode> q2 = new LinkedList<>() ;
q1.add(0) ;
q2.add(root) ;
while(! q1.isEmpty()){
int c = q1.poll() ;
TreeNode node = q2.poll() ;
if(! col.containsKey(c)){
col.put(c , new ArrayList<Integer>()) ;
}
col.get(c).add(node.val) ;
col_min = Math.min(col_min , c) ;
col_max = Math.max(col_max , c) ;
if(node.left != null){
q1.add(c-1) ;
q2.add(node.left) ;
}
if(node.right != null){
q1.add(c+1) ;
q2.add(node.right) ;
}
}
for(int i = col_min ; i <= col_max ; i++){
ans.add(col.get(i)) ;
}
return ans ;
}
}