zoukankan      html  css  js  c++  java
  • [leetcode]366. Find Leaves of Binary Tree捡树叶

    Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

    Example:

    Input: [1,2,3,4,5]
      
              1
             / 
            2   3
           /      
          4   5    
    
    Output: [[4,5,3],[2],[1]]

    Explanation:

    1. Removing the leaves [4,5,3] would result in this tree:

              1
             / 
            2          

    2. Now removing the leaf [2] would result in this tree:

       1  

    3. Now removing the leaf [1] would result in the empty tree:

              []         

    题意:

    逐层移除二叉树的叶节点。

    Solution1: DFS

    解本题需要的背景知识: 【height】The height of a node is the number of edges from the node to the deepest leaf.

    For instance,

    node 1 has height of 2
    node 2 has height of 1
    node 4 has height of 0
    node 5 has height of 0
    node 3 has height of 0
    Based on the output, we need to gather up all the nodes with height 0, we then gather up all the nodes with height 1, and then all the nodes with height 2

    所以我们的target就是边traversal given tree边拿到each node's height, 把不同height的node放到result里

    code

     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 class Solution {
    11    public List<List<Integer>> findLeaves(TreeNode root) {
    12         List<List<Integer>> res = new ArrayList<>();
    13         helper(res, root);
    14         return res;
    15     }
    16     //helper function to return the height of current node
    17     private int helper(List<List<Integer>> res, TreeNode root) {
    18         if (root == null) return -1;
    19         int left = helper(res, root.left);
    20         int right = helper(res, root.right);
    21         int height = Math.max(left, right) + 1;
    22         if (res.size() == height) {
    23             res.add(new ArrayList<>());
    24         }
    25         res.get(height).add(root.val);
    26         return height;
    27     }
    28 }
  • 相关阅读:
    【原】如何实现IE6下块级元素的内容自动收缩
    【原】常见的模块,你语义化了没
    【转】CSS Nuggest
    那年,寻找工作的历程
    前端开发小工具SuperApp——Ctrl+S自动刷新浏览器
    【转】在html中引入CSS的方法
    HTML中常用的实体字符
    imemode:disabled 禁止表单使用文本框输入法
    【原】工作中常用win7快捷键
    复制本地文件完整路径
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10014700.html
Copyright © 2011-2022 走看看