Problem 439526 · medium · Phase 04 Non-Linear Data Structures

Trim Away Leaves of a Given Value

binary tree · recursion · post-order · in-place modification

Given the root of a tree and an integer target, delete every leaf whose value is target. If that deletion turns a parent into a leaf whose value is also target, delete it too, and keep going until no such leaf remains. Return the root of the result (None if everything was removed).

Examples

      1
     / \
    2   3
   /   / \
  2   2   4

Input:  root = build_tree([1, 2, 3, 2, None, 2, 4]), target = 2
Output: tree_to_list(...) == [1, None, 3, None, 4]
Explanation: the leaf 2 under the left 2 goes first, which makes that 2 a leaf, so it goes as well.

Input:  root = build_tree([1, 1, 1]), target = 1
Output: []

Constraints

  • 0 <= number of nodes <= 1000
  • -100 <= node.val, target <= 100

Goals

  • Recognise that one post-order pass handles a 'repeat until stable' rule
  • Return updated child pointers from the recursion
Starting Python…