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].

 1 class TreeNode {
 2     int val;
 3     TreeNode left;
 4     TreeNode right;
 5 
 6     TreeNode(int x) {
 7         val = x;
 8     }
 9 };
10 
11 class Solution { 
12     public List<List<Integer>> findLeaves(TreeNode root) {
13         List<List<Integer>> listAll = new ArrayList<List<Integer>>();
14         while (root != null) {
15             List<Integer> list = new ArrayList<Integer>();
16             root = helper(list, root);
17             listAll.add(new ArrayList<Integer>(list));
18         }
19 
20         return listAll;
21     }
22 
23     private TreeNode helper(List<Integer> list, TreeNode root) {
24         if (root == null)
25             return null;
26 
27         if (root.left == null && root.right == null) {
28             list.add(root.val);
29             return null;
30         }
31 
32         root.left = helper(list, root.left);
33         root.right = helper(list, root.right);
34 
35         return root;
36     }
37 }

 下面这种方法是不会移除leaves的。

 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>> res = new ArrayList<>();
13         height(root, res);
14         return res;
15     }
16     private int height(TreeNode node, List<List<Integer>> res){
17         if(null==node)  return 0;
18         int level = 1 + Math.max(height(node.left, res), height(node.right, res));
19         if(res.size() == level - 1)  res.add(new ArrayList<>());
20         res.get(level - 1).add(node.val);
21         return level;
22     }
23 }

 

posted @ 2016-07-26 01:03  北叶青藤  阅读(208)  评论(0)    收藏  举报