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 }
  • 相关阅读:
    爬虫项目数据解析方式
    数据分析
    爬虫项目代理操作和线程池爬取
    Python网络爬虫
    Django多表操作
    网络编程
    python中什么是元类
    Python面向对象中super用法与MRO机制
    mysql之pymysql
    mysql之索引原理
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810531.html
Copyright © 2011-2022 走看看