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 }
  • 相关阅读:
    【flutter BottomNavigationBar 】selectedLabelStyle: TextStyle(fontSize: 22) 更新后使用方法
    学术论文中的参考文献格式
    word2016中写出伪代码
    基于RPLiDAR A2的cartographer建图
    第 7 章 系统效果评测与监控
    Linux TOP 命令详解
    mysql-canal-rabbitmq 安装部署教程
    第 6 章 用户画像系统
    Elasticsearch 模块
    Kibana 插件环境搭建教程
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810531.html
Copyright © 2011-2022 走看看