Construct Binary Tree from Preorder and Inorder Traversal
Description
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
Return the following binary tree:
Solution
preorder traversal of root = [root->val, preorder traversal of root->left, preorder traversal of root->right].
inorder traversal of root = [inorder traversal of root->left, root->val, inorder traversal of root->right].
Since there are no duplicates, we can use a hash table to quickly get the index of root->val in the inorder traversal of root, denoted as rootIdx
. Then the preorder traversal of root-left is preorder[1:rootIdx]
, including preorder[rootIdx].
Then we just need to solve two smaller problems.
Last updated