Instructions
You are given two lists of numbers, preorder and inorder. They come from the same binary tree:
preorderlists the values in preorder: the node first, then its whole left subtree, then its whole right subtree;inorderlists the values in inorder: the whole left subtree first, then the node, then the whole right subtree.
Build this tree and return its root. All values in the tree are different, so there is exactly one such tree. If the lists are empty, return null (None in Python).
How the input is shown
preorder and inorder are plain lists of numbers. The tree you return is shown as a list of values in level order: row by row from the top, and left to right in each row. null means "no child here", and nulls at the end are left out. For example, [4, 2, 7, null, 3] is a root 4 with left child 2 and right child 7, and 2 has only a right child, 3.
Build the tree from TreeNode objects (new TreeNode(val) in JavaScript, TreeNode(val) in Python) and set their left and right fields.
Hint: the first value of preorder is the root. Find it in inorder: the values to its left form the left subtree, and the values to its right form the right subtree. A map from value to its index in inorder makes each lookup fast.
Examples
Example 1
- Input:
- [7,2,5,9,1,8], [5,2,7,1,9,8]
- Output:
- [7,2,9,5,null,1,8]
The root is 7, the first value of preorder. In inorder, 5 and 2 are left of 7 and 1, 9, 8 are right of it. Doing the same on each side gives 2 with left child 5, and 9 with children 1 and 8.
Example 2
- Input:
- [-4], [-4]
- Output:
- [-4]
There is only one value, so the tree is a single node.
Example 3
- Input:
- [1,6,3], [6,3,1]
- Output:
- [1,6,null,null,3]
The root is 1. In inorder, 6 and 3 are both left of 1, so 1 has no right child. In that left part, 6 comes first in preorder, so 6 is the left child of 1, and 3 (right of 6 in inorder) is the right child of 6.
Constraints
0 <= preorder.length <= 35inorder.length == preorder.length-100 <= value <= 100- All values are different.
preorderandinorderalways come from the same binary tree.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [7,2,5,9,1,8], [5,2,7,1,9,8]
- Expected:
- [7,2,9,5,null,1,8]
- Input:
- [-4], [-4]
- Expected:
- [-4]
- Input:
- [1,6,3], [6,3,1]
- Expected:
- [1,6,null,null,3]
Run checks your code against the 3 examples. Submit checks it against all 123 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.