Leetcode Problem 105. Construct Binary Tree from Preorder and Inorder Traversal
105. Construct Binary Tree from Preorder and Inorder Traversal
AI Mock Interview
Leetcode Solutions
Approach: Recursion
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Create a hashmap to store the value to index mapping for the inorder array.
Define a helper function
arrayToTree
that takes two indices as the range of the current subtree in the inorder array.
If the range is empty, return
null
.
Initialize the root with
preorder[preorderIndex]
and increment
preorderIndex
.
Find the root index in the inorder array using the hashmap.
Recursively construct the left subtree using the range before the root index in the inorder array.
Recursively construct the right subtree using the range after the root index in the inorder array.
Return the root node.
Call the helper function with the full range of the inorder array to construct the entire tree.
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...