• 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 }
  • 相关阅读:
    Linux C编程之十二 信号
    折腾vue--vue自定义组件(三)
    折腾vue--使用vscode创建vue项目(二)
    折腾vue--环境搭建(一)
    .net生成PDF文件的几种方式
    星星评分-依赖jquery
    组织机构树
    Newtonsoft--自定义格式化日期
    .net mvc 自定义错误页面
    js模拟form提交 导出数据
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6403759.html
Copyright © 2020-2023  润新知