zoukankan      html  css  js  c++  java
  • *Binary Tree Vertical Order Traversal

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

    Given binary tree [3,9,20,4,5,2,7],

        _3_
       /   
      9    20
     /    / 
    4   5 2   7
    

    return its vertical order traversal as:

    [
      [4],
      [9],
      [3,5,2],
      [20],
      [7]
    ]
    
     1 public class Solution {
     2     public List<List<Integer>> verticalOrder(TreeNode root) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         if (root == null) {
     5             return res;
     6         }
     7        //map's key is column, we assume the root column is zero, the left node will minus 1 ,and the right node will plus 1
     8         HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
     9         Queue<TreeNode> queue = new LinkedList<>();
    10        //use a HashMap to store the TreeNode and the according cloumn value
    11         HashMap<TreeNode, Integer> weight = new HashMap<TreeNode, Integer>();
    12         queue.offer(root);
    13         weight.put(root, 0);
    14         int min = 0;
    15         while (!queue.isEmpty()) {
    16             TreeNode node = queue.poll();
    17             int w = weight.get(node);
    18             if (!map.containsKey(w)) {
    19                 map.put(w, new ArrayList<>());
    20             }
    21             map.get(w).add(node.val);
    22             if (node.left != null) {
    23                 queue.add(node.left);
    24                 weight.put(node.left, w - 1);
    25             } 
    26             if (node.right != null) {
    27                 queue.add(node.right);
    28                 weight.put(node.right, w + 1);
    29             }
    30             //update min ,min means the minimum column value, which is the left most node
    31             min = Math.min(min, w);
    32         }
    33         while (map.containsKey(min)) {
    34             res.add(map.get(min++));
    35         }
    36         return res;
    37     }
    38 }

    reference:https://leetcode.com/discuss/73113/using-hashmap-bfs-java-solution

  • 相关阅读:
    2010年10月全球web服务器调查
    Orchard 发布1.0版本和ASP.NET MVC 3 RTM
    推荐一个在Linux/Unix上架设ASP.NET的 WEB服务器Jexus
    Windows Azure 的成本架构
    RavenDB系列教程
    Mono环境下不支持中文的解决方法
    IIS 7.0的六大安全新特性为你的Web服务器保驾护航
    Windows 7 Phone 文档数据库Rapid Repository正式发布
    使用log4Net 输出日志到mongodb
    Ubuntu & Fedora Mono 2.8 安装脚本
  • 原文地址:https://www.cnblogs.com/hygeia/p/5081430.html
Copyright © 2011-2022 走看看