Find Leaves of Binary Tree
Medium
Topics
Given the root of a binary tree, collect its nodes as follows: take all the leaves and remove them, then take all the leaves of what is left and remove those, and so on until the tree is empty.
Return the collected groups in the order they were removed.
Within a group, list the values left to right as they stood in the tree, so the answer is unambiguous.
On this judge the groups are shown separated by |.
Example 1
[[4,5,3],[2],[1]].null marks a missing child.Input: root = [1,2,3,4,5] Output: [[4,5,3],[2],[1]] Explanation: The first round removes 4, 5 and 3. That leaves 1 with a single child 2, which is removed next, and finally the root.
Example 2
Input: root = [1] Output: [[1]] Explanation: The root is itself a leaf, so one round empties the tree.
Example 3
Input: root = [1,2,null,3] Output: [[3],[2],[1]] Explanation: A left-leaning chain peels one node per round.
Constraints
- 1 <= number of nodes <= 100
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Repeatedly scanning for leaves and deleting them is the literal reading, and it rebuilds the same information over and over. The useful reframing is to ask, for each node, which round will remove it.
A node is removed once both its subtrees are gone. So its round is one more than the later of its children’s rounds — which is exactly the node’s height, the distance to its deepest descendant leaf. A leaf has height 0 and goes in round 0; its parent has height 1 and goes in round 1.
That turns the whole thing into a single traversal: compute each node’s height bottom-up and file its value under that height. No node is ever deleted and no round is ever re-scanned.
Approach
- Recurse to the bottom of the tree, returning each node’s height. An absent child contributes height
-1so a leaf comes out as 0. - At each node, take one more than the larger of its two children’s heights.
- Append the node’s value to the group indexed by that height, creating the group the first time it is reached.
- Visit the left subtree before the right, which fills every group left to right as the statement requires. Return the groups in index order.
Walkthrough
root = [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
node height group
4 0 0: [4]
5 0 0: [4,5]
2 1 1: [2]
3 0 0: [4,5,3]
1 2 2: [1]
answer [[4,5,3],[2],[1]]
Note 3 joins group 0 after 5 even though it sits higher
in the tree -- the group is by removal round, and within
it the order is left to right.Complexity
- Time — O(n): one visit per node, with constant work each. The repeated-deletion reading is O(n²) on a path-shaped tree.
- Space — O(n): the recursion depth, which is the tree height, plus one stored value per node in the groups.
Common Pitfalls
- Using depth from the root rather than height from the leaves. Those only agree on a perfectly balanced tree — in example 1 the node 3 has depth 1 but height 0, and it belongs with the leaves.
- Visiting the right subtree first, which reverses the order within each group.
- Returning
0for an absent child instead of-1, which puts every leaf in group 1 and leaves group 0 empty.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findLeaves(self, root):
groups = []
def height(node):
if not node:
return -1
h = 1 + max(height(node.left), height(node.right))
if h == len(groups):
groups.append([])
groups[h].append(node.val)
return h
height(root)
return groupsimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
groups = new ArrayList<>();
height(root);
return groups;
}
private List<List<Integer>> groups;
private int height(TreeNode node) {
if (node == null) return -1;
int h = 1 + Math.max(height(node.left), height(node.right));
if (h == groups.size()) groups.add(new ArrayList<>());
groups.get(h).add(node.val);
return h;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> groups;
function<int(TreeNode*)> height = [&](TreeNode* node) -> int {
if (!node) return -1;
int h = 1 + max(height(node->left), height(node->right));
if (h == (int)groups.size()) groups.push_back({});
groups[h].push_back(node->val);
return h;
};
height(root);
return groups;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {number[][]}
*/ var findLeaves = function(root) {
const groups = [];
const height = (node) => {
if (!node) return -1;
const h = 1 + Math.max(height(node.left), height(node.right));
if (h === groups.length) groups.push([]);
groups[h].push(node.val);
return h;
};
height(root);
return groups;
};