加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

314.Binary Tree Vertical Order Traversal

发布时间:2020-12-14 03:50:46 所属栏目:大数据 来源:网络整理
导读:314 .?Binary Tree Vertical Order Traversal class Solution { public ListListInteger verticalOrder(TreeNode root) { HashMap Integer,ListInteger map = new HashMap (); List ListInteger result = new ArrayList (); Queue TreeNode queue = new Link
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;
    }
}
        
        

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读