• [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 }
  • 相关阅读:
    Shell 查找和关闭进程
    如何重启MySQL,正确启动MySQL
    php 杂记
    Linux gcc编译简介、常用命令
    memset和printf(buf)编译出错
    Linux 文件操作函数
    Sizeof与Strlen的区别与联系
    获取Checkbox的值
    undefined reference to 'pthread_create'
    linux makefile文件
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810531.html
Copyright © 2020-2023  润新知