Given the root of a binary tree, collect a tree's nodes as if you were doing this:
Collect all the leaf nodes.
Remove all the leaf nodes.
Repeat until the tree is empty.
Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
- return every level leaf nodes as a list
Bottom-up Recursive approach:
- use maxDepth to calculate if the nodes go to the same level list
- since it's bottom-up, at the ground level, the return list should gather all nodes in that level and then working up the tree
- at the original level of leaf nodes, the level is 0 and then adds up when returning back up
Time: O(n)
Space: O(n)
Recursive
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> findLeaves(TreeNode root) {
maxHeight(root);
return ans;
}
private int maxHeight(TreeNode root) {
if (root == null)
return -1;
int height = Math.max(maxHeight(root.left), maxHeight(root.right)) + 1;
if (height == ans.size())
ans.add(new ArrayList<>());
ans.get(height).add(root.val);
return height;
}