105. Construct Binary Tree from Preorder and Inorder Traversal ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Binary Tree
, Divide and Conquer
, Recursion
Given two integer arrays preorder
and inorder
:
preorder
represents the preorder traversal of a binary tree.
inorder
represents the inorder traversal of the same binary tree.
Construct and return the binary tree.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
and inorder
consist of unique values.
Each value in inorder
also appears in preorder
.
preorder
is guaranteed to be the preorder traversal of the tree.
inorder
is guaranteed to be the inorder traversal of the tree.
To construct the binary tree:
The first value in preorder
is the root node.
Find the root node's position in inorder
. Values to the left belong to the left subtree, and values to the right belong to the right subtree.
Recursively repeat this process for the left and right subtrees.
Preorder Traversal:
The first element is the root.
Subsequent elements belong to the left or right subtree.
Inorder Traversal:
Left subtree elements come before the root.
Right subtree elements come after the root.
Recursive Construction:
Use the preorder
array to pick the root.
Divide the inorder
array into left and right subtrees.
Recursively construct the tree for both subtrees.
O(n), where n
is the number of nodes. Each node is visited once, and the HashMap
provides O(1)
lookups for the index.
O(n) for the HashMap
and recursive stack space.
What changes would you make to solve the problem if the tree was not guaranteed to have unique values?
How would the approach differ for constructing a binary search tree?
You can find the full solution here.