码迷,mamicode.com
首页 > 其他好文 > 详细

Find Leaves of Binary Tree 找二叉树的叶节点

时间:2016-07-21 00:21:36      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty.

Example:
Given binary tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1].

Explanation:
1. Remove the leaves [4, 5, 3] from the tree

1
/
2
2. Remove the leaf [2] from the tree 

  1  

3. Remove the leaf [1] from the tree

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

该题的重点是对tree进行剪枝活动时候,我们可以利用x = change(x) 在recursive函数中。例如, root.left = removeLeaves(root.left, result); root.right = removeLeaves(root.right, result), 这样下层内嵌函数返回的null值可以赋给上层调用函数的root.left/right。 因此递归函数的返回类型很自然应该设为TreeNode

 1 public class Solution {
 2     private TreeNode removeLeaves(TreeNode root, List<Integer> result)
 3     {
 4         if(root==null)  return null;
 5         if((root.left == null)&&(root.right==null)){
 6             result.add(root.val);
 7             return null;
 8         }
 9         
10         root.left = removeLeaves(root.left, result);
11         root.right = removeLeaves(root.right, result);
12         
13         return root;
14 
15     }
16     
17     public List<List<Integer>> findLeaves(TreeNode root) {
18         List<List<Integer>> res = new ArrayList<List<Integer>>();
19         if (root==null) return res;
20         while(root!=null){
21             List<Integer> leaves = new ArrayList<Integer>();
22             root = removeLeaves(root, leaves);
23             res.add(leaves);
24         }
25         
26         return res;
27     }
28 }

 

 

 

 

 

 

 

1
3. Remove the leaf [1] from the tree

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

Find Leaves of Binary Tree 找二叉树的叶节点

标签:

原文地址:http://www.cnblogs.com/unlockleetcode/p/5689985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!