• *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

  • 相关阅读:
    最短路计数
    轻拍牛头(类埃式筛)
    子序列(尺取模板题)
    状压dp(洛谷:互不侵犯)
    刷题-力扣-73. 矩阵置零
    刷题-力扣-150. 逆波兰表达式求值
    刷题-力扣-300. 最长递增子序列
    刷题-力扣-1576. 替换所有的问号
    刷题-力扣-54. 螺旋矩阵
    刷题-力扣-705. 设计哈希集合
  • 原文地址:https://www.cnblogs.com/hygeia/p/5081430.html
Copyright © 2020-2023  润新知