首页 > 其他 > 详细

Find Leaves of Binary Tree

时间:2017-02-15 23:55:34      阅读:308      评论:0      收藏:0      [点我收藏+]

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 }

 

Find Leaves of Binary Tree

原文:http://www.cnblogs.com/amazingzoe/p/6403759.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!