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 1

Naively, we can get the order of each node, store them in a hashmap and then iterate over the hashmap to get the list.

public List<List<Integer>> findLeaves(TreeNode root) {
    HashMap<TreeNode, Integer> map=new HashMap<>();
    helper(root, map);
 
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    HashMap<Integer, HashSet<TreeNode>> reversed = new HashMap<>();
 
    for(Map.Entry<TreeNode, Integer> entry: map.entrySet()){
        min = Math.min(min, entry.getValue());
        max = Math.max(max, entry.getValue());
 
        HashSet<TreeNode> set = reversed.getOrDefault(entry.getValue(), new HashSet<TreeNode>());
        set.add(entry.getKey());
        reversed.put(entry.getValue(), set);
    }
 
 
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    for(int i=min; i<=max; i++){
        HashSet<TreeNode> set = reversed.get(i);
        ArrayList<Integer> l = new ArrayList<>();
        for(TreeNode td: set){
            l.add(td.val);
        }
        result.add(l);
    }
 
    return result;
}
 
private int helper(TreeNode root, HashMap<TreeNode, Integer> map){
    if(root==null){
        return 0;
    }
 
    int left = helper(root.left, map);
    int right = helper(root.right, map);
 
    int order = Math.max(left, right)+1;
    map.put(root, order);
    return order;
}

Java Solution 2 - Optomized

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>
  • mg

    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);
    }

  • Iram22

    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;
    }