TREE-P2

Rebuild the tree

Practice 2 of 6Trees and BSTs8 tests

The problem

You are given the pre-order list and the in-order list of a binary tree (lesson 2). All values are different. Rebuild the tree and return its root.

build_tree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
#        3
#       / \
#      9   20
#         /  \
#        15   7

The values are not sorted: this is any binary tree, not a search tree. Use the TreeNode class from the starter code.

Limits

  • Up to 100,000 nodes; the tree is at most 300 levels deep, so recursion is fine.

Builds on TREE-3 Rebuilding a tree from traversals.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Small treeNot run
2EmptyNot run
3One nodeNot run
4The lessons' treeNot run
5Path to the leftNot run
6Path to the rightNot run
7Not a search treeNot run
8100,000 nodesNot run