Find Leaves of Binary Tree

medium tree dfs

Problem

Repeatedly remove leaves of a binary tree and collect them into groups, in the order they're removed.

Inputroot = [1,2,3,4,5]
Output[[4,5,3],[2],[1]]
First pass strips 4, 5, 3 (all leaves); then 2 becomes a leaf; finally the root 1.

def find_leaves(root):
    out = []
    def dfs(node):
        if not node: return -1
        d = max(dfs(node.left), dfs(node.right)) + 1
        if d == len(out): out.append([])
        out[d].append(node.val)
        return d
    dfs(root)
    return out
function findLeaves(root) {
  const out = [];
  function dfs(node) {
    if (!node) return -1;
    const d = Math.max(dfs(node.left), dfs(node.right)) + 1;
    if (d === out.length) out.push([]);
    out[d].push(node.val);
    return d;
  }
  dfs(root);
  return out;
}
class Solution {
    List> out = new ArrayList<>();
    public List> findLeaves(TreeNode root) { dfs(root); return out; }
    int dfs(TreeNode node) {
        if (node == null) return -1;
        int d = Math.max(dfs(node.left), dfs(node.right)) + 1;
        if (d == out.size()) out.add(new ArrayList<>());
        out.get(d).add(node.val);
        return d;
    }
}
class Solution {
    vector> out;
    int dfs(TreeNode* n) {
        if (!n) return -1;
        int d = max(dfs(n->left), dfs(n->right)) + 1;
        if (d == (int)out.size()) out.emplace_back();
        out[d].push_back(n->val);
        return d;
    }
public:
    vector> findLeaves(TreeNode* root) { dfs(root); return out; }
};
Time: O(n) Space: O(h)