zoukankan      html  css  js  c++  java
  • [leetcode]314. 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 1:

    Input: [3,9,20,null,null,15,7]
    
       3
      /
     /  
     9  20
        /
       /  
      15   7 
    
    Output:
    
    [
      [9],
      [3,15],
      [20],
      [7]
    ]

    思路

    代码

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<List<Integer>> verticalOrder(TreeNode root) {
    12         // corner
    13         List<List<Integer>> results = new ArrayList<>();
    14         if (root == null) return results;
    15         // init
    16         int min = Integer.MAX_VALUE;
    17         int max = Integer.MIN_VALUE;
    18         Map<Integer, List<Integer>> map = new HashMap<>();
    19         Queue<Position> queue = new LinkedList<>();
    20         
    21         //use queue to bfs
    22         queue.add(new Position(root, 0));
    23         while (!queue.isEmpty()) {
    24             Position position = queue.remove();
    25             min = Math.min(min, position.column);
    26             max = Math.max(max, position.column);
    27             List<Integer> list = map.get(position.column);
    28             if (list == null) {
    29                 list = new ArrayList<>();
    30                 map.put(position.column, list);
    31             }
    32             list.add(position.node.val);
    33             if (position.node.left != null) queue.add(new Position(position.node.left, position.column-1));
    34             if (position.node.right != null) queue.add(new Position(position.node.right, position.column+1));
    35         }
    36         for(int i = min; i<= max; i++) {
    37             List<Integer> list = map.get(i);
    38             if (list != null) results.add(list);
    39         }
    40         return results;
    41     }
    42 }
    43 
    44 class Position {
    45     TreeNode node;
    46     int column;
    47     Position(TreeNode node, int column) {
    48         this.node = node;
    49         this.column = column;
    50     }
    51 }
  • 相关阅读:
    Git哲学与使用
    save
    http://www.onvif.org/onvif/ver20/util/operationIndex.html
    图标
    C#高性能大容量SOCKET并发(一):IOCP完成端口例子介绍(转)
    一种基于PTP 协议的局域网高精度时钟同步方法(转)
    WPF中的数据模板(DataTemplate)(转)
    WPF中的ControlTemplate(控件模板)(转)
    也来说说C#异步委托(转)
    C#委托的介绍(delegate、Action、Func、predicate)(转)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810531.html
Copyright © 2011-2022 走看看