Construct Binary Tree from Preorder and Inorder
Given two integer arrays preorder and inorder representing the preorder and inorder traversals of a binary tree with unique values, reconstruct and return the tree.
Open official problem prompt ↗Rebuild the unique binary tree that produced the given preorder and inorder traversals.
Like reassembling a book from a table of contents (preorder tells you which chapter starts next) and an index (inorder tells you what falls before and after each chapter title).
- Input
- preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
- Output
- [3, 9, 20, null, null, 15, 7]
- Why
- 3 is the root; in inorder, 9 is left of 3 and [15,20,7] are right, matching the reconstructed tree.
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= values <= 3000preorder and inorder consist of unique valuesinorder is a permutation of preorder