Medium 314题 Binary Tree Vertical Order Traversal

Question:

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]
    ]

Solution:

/**
 * 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>> res=new ArrayList<List<Integer>>();
        if(root == null) return res;
        Map<Integer, ArrayList<Integer>> map=new HashMap<Integer, ArrayList<Integer>>();
        Queue<TreeNode> p=new LinkedList<TreeNode>();
        Queue<Integer> cols=new LinkedList<Integer>();
        
        int min=0;
        int max=0;
        
        p.add(root);
        cols.add(0);
        
        while(!p.isEmpty())
        {
            TreeNode node=p.poll();
            int col=cols.poll();
            if(!map.containsKey(col)) map.put(col,new ArrayList<Integer>());
            map.get(col).add(node.val);
            
            if(node.left!=null)
            {
                p.add(node.left);
                cols.add(col-1);
                min=Math.min(col-1,min);
            }
            
            if(node.right!=null)
            {
                p.add(node.right);
                cols.add(col+1);
                max=Math.max(col+1,max);
            }
        }
        
        for(int i=min;i<=max;i++)
            res.add(map.get(i));
        return res;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值