Build a tree from pre-order and in-order
Challenge · Write code · about 20 min
Given two lists preorder and inorder that come from the same binary tree with distinct values, rebuild the tree and return its root.
The first pre-order value is the root. Its position in the in-order list splits the other values into the left and right subtree.
Example 1
Input:
[[3,9,20,15,7],[9,3,15,20,7]]
Output:
[3,9,20,null,null,15,7]
The tree is shown in level order.
Example 2
Input:
[[1,2],[2,1]]
Output:
[1,2]
Constraints
- 0 ≤ number of nodes ≤ 1,000
- All values are distinct
- The two lists describe the same tree
Learn the idea first: Pre-order, in-order, post-order, a visual lesson.
More Pre-order, in-order, post-order problems
- Write the three orders Warm-up
- In-order of a search tree Warm-up
- Complete the in-order traversal Warm-up
- Pre-order traversal Standard
- Post-order traversal Standard
- In-order iteratively Standard
- Fix the post-order traversal Standard