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.

Given binary tree

         / \
        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){
        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.
        list.add(new ArrayList<Integer>());
    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:
String foo = "bar";

  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);}
    List list=new ArrayList();
    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()) {
    } while (!results.isEmpty());
    return returnResults;

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

Leave a comment