LeetCode – Find Leaves of Binary Tree (Java)

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

Java Solution

The key to solve this problem is converting the problem to be finding the index of the element in the result list. Then this is a typical DFS problem on trees.

public List<List<Integer>> findLeaves(TreeNode root) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    helper(result, root);
    return result;
}
 
// traverse the tree bottom-up recursively
private int helper(List<List<Integer>> list, TreeNode root){
    if(root==null)
        return -1;
 
    int left = helper(list, root.left);
    int right = helper(list, root.right);
    int curr = Math.max(left, right)+1;
 
    // the first time this code is reached is when curr==0,
    //since the tree is bottom-up processed.
    if(list.size()<=curr){
        list.add(new ArrayList<Integer>());
    }
 
    list.get(curr).add(root.val);
 
    return curr;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Iram22 on 2017-2-13

    private static int findleaves(Node n,HashMap<Integer,List> map){
    if(n==null) return 0;
    int l=findleaves(n.left,map);
    int r=findleaves(n.right,map);
    int x=Math.max(l,r)+1;
    if(map.containsKey(x)){ map.get(x).add(n.val);}
    else{
    List list=new ArrayList();
    list.add(n.val);
    map.put(x,list);
    }
    return x;
    }

  2. mg on 2017-5-11

    public List<List> findLeaves(TreeNode root) {
    List<List> returnResults = new ArrayList();
    List results = new ArrayList();
    Set alreadyChecked = new HashSet();
    do {
    results = new ArrayList();
    findLeaves(root, alreadyChecked, results);
    if (!results.isEmpty()) {
    returnResults.add(results);
    }
    } while (!results.isEmpty());
    return returnResults;
    }

    void findLeaves(TreeNode node, Set alreadyChecked, List results) {
    if (node == null) {
    return;
    }
    if ((alreadyChecked.contains(node.left) || node.left == null)
    && (alreadyChecked.contains(node.right) || node.right == null)) {
    if (alreadyChecked.add(node)) {
    results.add(node.val);
    }
    }
    findLeaves(node.left, alreadyChecked, results);
    findLeaves(node.right, alreadyChecked, results);
    }

Leave a comment

*