zoukankan      html  css  js  c++  java
  • *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

  • 相关阅读:
    任意文件读取与下载漏洞
    命令执行与代码执行漏洞原理
    安全面试知识汇总
    科学使用Github(gayhub)搜索想要的项目
    业务逻辑漏洞--注册-登录-改密码页面总结
    Linux提权之SUID提权
    攻防世界XCTF--伪造请求头XFF和Referer(第九题)
    攻防世界XCTF--两种传输方式get_post(第八题)
    攻防世界XCTF--一个简单的PHP后端验证(第七题)
    课时14.DTD文档声明上(掌握)
  • 原文地址:https://www.cnblogs.com/hygeia/p/5081430.html
Copyright © 2011-2022 走看看