Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 1.61 KB

0366.md

File metadata and controls

60 lines (42 loc) · 1.61 KB

Level: Medium

Topic: Tree Binary Tree Depth First Search

Question

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.

Intuition

  • return every level leaf nodes as a list

Bottom-up Recursive approach:

  1. use maxDepth to calculate if the nodes go to the same level list
  2. 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
  3. at the original level of leaf nodes, the level is 0 and then adds up when returning back up

Code

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;
}