Skip to contentKEEP THE CRAFTTHE SANCTUARY

Partition Traversal Ranges

List the index ranges you split when rebuilding a binary tree from its preorder and inorder traversals.

The problem

Implement partition_traversal_ranges(preorder, inorder). Both lists describe the same binary tree, and all values are distinct. To rebuild a tree from these two traversals, you split them again and again: the first value of a preorder range is the root of that subtree, and the root's position in the inorder range separates its left subtree from its right subtree. Return every non-empty range as [pre_left, pre_right, in_left, in_right], where preorder[pre_left:pre_right] and inorder[in_left:in_right] hold the same subtree (right ends are exclusive, like slices). Start with the whole tree, and list each subtree's range before all the ranges of its left subtree, followed by all the ranges of its right subtree. Two empty lists give [].

Starter code

def partition_traversal_ranges(preorder, inorder):
    pass

Public examples

  1. preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]gives[[0, 5, 0, 5], [1, 2, 0, 1], [2, 5, 2, 5], [3, 4, 2, 3], [4, 5, 4, 5]]
  2. preorder = [1], inorder = [1]gives[[0, 1, 0, 1]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.