zoukankan      html  css  js  c++  java
  • 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:
    Given binary tree 

              1
             / 
            2   3
           /      
          4   5    
    

    Returns [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:

              []         
    

    Returns [4, 5, 3], [2], [1].

    Credits:
    Special thanks to @elmirap for adding this problem and creating all test cases.

     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>> findLeaves(TreeNode root) {
    12         List<List<Integer> > result = new ArrayList<>();
    13         helper(root, result);
    14         return result;
    15     }
    16     
    17     private int helper(TreeNode root, List<List<Integer> > result) {
    18         if (root == null) return -1;
    19         int depth = 1 + Math.max(helper(root.left, result), helper(root.right, result));
    20         if (result.size() < depth + 1) result.add(new ArrayList<Integer>());
    21         result.get(depth).add(root.val);
    22         
    23         return depth;
    24     }
    25 }
  • 相关阅读:
    P1456 Monkey King
    P3377 【模板】左偏树(可并堆)
    P1074 靶形数独
    P1120 小木棍
    P5490 【模板】扫描线
    糖糖别胡说,我真的不是签到题目
    最长公共子序列
    最长上升子序列
    数的三次方根
    地、颜色、魔法(dfs)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6403759.html
Copyright © 2011-2022 走看看