Problem 439526 · medium · Level 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

      6
     / \
    5   5
   /   / \
  5   8   5
           \
            5

Input:  root = build_tree([6, 5, 5, 5, None, 8, 5, None, None, None, None, None, 5]), target = 5
Output: tree_to_list(...) == [6, None, 5, 8]
Explanation: the leaf 5 under the left 5 goes first, which makes that 5 a leaf, so it goes as well. On the right the bottom 5 goes, then its parent; the root's right child 5 still has 8 below it, so it stays.

Input:  root = build_tree([4, 4, None, 4, 4]), target = 4
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…