微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

314. Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal


class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
      HashMap<Integer,List<Integer>> map = new HashMap<>();
      List<List<Integer>> result = new ArrayList<>();
      Queue<TreeNode> queue = new LinkedList<>();
      Queue<Integer> cols = new LinkedList<>();
      
      if(root == null){
        return result;
      }
      
      int max = 0;
      int min = 0;
      
      queue.offer(root);
      cols.offer(0);
      while(!queue.isEmpty()){
        TreeNode cur = queue.poll();
        int col = cols.poll();
        if(!map.containsKey(col)){
          map.put(col,new ArrayList<Integer>());
        }
        map.get(col).add(cur.val);
        
        if(cur.left != null){
          queue.offer(cur.left);
          cols.offer(col - 1);
          min = Math.min(min,col - 1);
        }
        
        if(cur.right != null){
          queue.offer(cur.right);
          cols.offer(col + 1);
          max = Math.max(max,col + 1);
        }
      }
      
      for(int i = min; i <= max; i++){
        List<Integer> current_col = map.get(i);
        result.add(current_col);
      }
      return result;
    }
}
        
        

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐