Problem 477064 · medium · Level 04 Non-Linear Data Structures

Flatten a Tree Into a Right-Leaning Chain

binary tree · recursion · in-place modification · preorder

Rearrange the tree in place so that every node's left pointer is None and the right pointers form a single chain that lists the nodes in preorder (node, then its left subtree, then its right subtree). Return the root. Do not create new nodes.

Examples

        7
      /   \
     3     9
      \   /
       5 2
      /
     8

Input:  root = build_tree([7, 3, 9, None, 5, 2, None, 8])
Output: tree_to_list(...) == [7, None, 3, None, 5, None, 8, None, 9, None, 2]

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

The tests also use flattened_original(root): it calls flatten_right(root) and returns tree_to_list(root) of the tree you were given, so a chain built from new nodes leaves the original unchanged and fails.

Constraints

  • 0 <= number of nodes <= 1000

Goals

  • Rewire pointers in place without losing the subtree that has not been processed yet
  • Use reverse post-order so the previously finished node becomes the next right child
Starting Python…