Ctrl K

Prune Marked Leaves

Medium
You get the root root of a binary tree and a number mark. Remove every leaf whose value equals mark. Once a leaf is removed, its parent may become a leaf itself. If that parent also holds mark, remove it as well, and keep going until no leaf with the value mark is left. Return the root of the resulting tree, or an empty tree if everything was removed.
Example 1
root=tree_node([4, 7, 9, 7, None, 7, 7]), mark=7 → [4, None, 9]

First the three leaves holding 7 are cut. Then the root's left child, also 7, becomes a leaf and goes too. Node 9 is now childless, but its value is not 7, so it stays.

Example 2
root=tree_node([5, 5, None, 5]), mark=5 → None

The chain of 5s is cut from the bottom up, root included, leaving an empty tree.

Example 3
root=tree_node([3, 8, 2, None, 6]), mark=8 → [3, 8, 2, None, 6]

Node 8 is not a leaf since it has the child 6, so nothing is removed.

Constraints
  • The tree has between 1 and 10⁵ nodes
  • 1 ≤ node value ≤ 1000
  • 1 ≤ mark ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([4, 7, 9, 7, None, 7, 7]), mark=7
Expected
[4, None, 9]

Run checks the first 3 tests in your browser. Submit checks all 32 tests on the server, hidden ones included.