105. Construct Binary Tree from Preorder and Inorder Traversal
Last updated
Was this helpful?
Last updated
Was this helpful?
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:
Thoughts:
Given preorder root preorder[preStart]: Find the corresponding index in the inorder array i, then [inStart ... i - 1] is the left tree, and [i + 1, inEnd] is the right tree. Base case: either preStart out of right bounds or inStart > inEnd.
Iterative Solution: from 's : 1. Keep pushing the nodes from the preorder into a stack (and keep making the tree by adding nodes to the left of the previous node) until the top of the stack matches the inorder.
At this point, pop the top of the stack until the top does not equal inorder (keep a flag to note that you have made a pop).
Repeat 1 and 2 until preorder is empty. The key point is that whenever the flag is set, insert a node to the right and reset the flag.
Code: Recursive: T:(NlogN),
Code: Iterative: T: O()