366 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
    
  1. Now removing the leaf [1] would result in the empty tree:
          []

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

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public List<List<Integer>> findLeaves(TreeNode root) {
        if(root== null) return new ArrayList<List<Integer>>();

        List<List<Integer>> l = findLeaves(root.left);
        List<List<Integer>> r = findLeaves(root.right);

        List<Integer> list = new ArrayList<>();
        list.add(root.val);


        if(l == null && r == null){
            List<List<Integer>> res = new ArrayList<>();
            res.add(list);
            return res;
        }else if(l == null || r == null){
            List<List<Integer>> res = l == null ? r : l;
            res.add(list);
            return res;
        }else{
            List<List<Integer>> lli = l.size() > r.size() ? merge(l,r): merge(r,l);
            lli.add(list);
            return lli;
        }

    }

    private List<List<Integer>> merge(List<List<Integer>> large, List<List<Integer>> small){
        for(int i=0; i< small.size(); i++){
            large.get(i).addAll(small.get(i));
        }
        return large;
    }
}

AND the concept of Tree Depth, which the root node has most deepest depth. and left has depth of 0.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> findLeaves(TreeNode root) {

        find(root);
        return res;
    }

    private int find(TreeNode root){
        if(root == null) return -1;

        int depth = Math.max(find(root.left), find(root.right)) +1;
        if(depth >= res.size()){
            res.add(new ArrayList<>());
        }

        res.get(depth).add(root.val);
        return depth;
    }
}

results matching ""

    No results matching ""