Wednesday, September 5, 2018

Leetcode 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:
Input: [1,2,3,4,5]
  
          1
         / \
        2   3
       / \     
      4   5    

Output: [[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:
          []         

Solution:
DFS + backtracking. Get depth of each node, and group the nodes with the same depth together.

Code (Java):
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        
        if (root == null) {
            return ans;
        }
        
        findLeavesHelper(root, ans);
        
        return ans;
    }
    
    private int findLeavesHelper(TreeNode root, List<List<Integer>> ans) {
        if (root == null) {
            return -1;
        }
        
        int left = findLeavesHelper(root.left, ans);
        int right = findLeavesHelper(root.right, ans);
        
        int depth = Math.max(left, right) + 1;
        
        if (depth == ans.size()) {
            List<Integer> list = new ArrayList<>();
            list.add(root.val);
            ans.add(list);
        } else {
            List<Integer> list = ans.get(depth);
            list.add(root.val);
        }
        
        
        return depth;
    }
}

1 comment:

  1. Though the output is right, but it's not removing the leaves from the tree. So it's incorrect. One way to solve is to set root.left = null, root.right = null after findLeavesHelper() recursive call.

    ReplyDelete