Problem
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
1 | |
Return the following binary tree:
1 | |
Explanation
-
We know that in the
preorderarray, the first element is the root of the tree. We can find this value also in theinorderarray. For example,preorder[] = {1, 2, 4, 3, 5}, andinorder[] = {4, 2, 1, 5, 3}, and the tree is illustrated below:1
2
3
4
51 / \ 2 3 / / 4 5 -
From the above illustration, we see that the root node
1is the first value ofpreorder, and we can find it in theinorderarray at the third element. So, in theinorderarray, any elements before1is from the left subtree, which are 4 and 2, and so in thepreorderarray, its next two elements 2 and 4 are from the left subtree too; in theinorderarray, any elements after1is from the right subtree, which are 5 and 3, and so in thepreorderarray, its next two elements 3 and 5 are from the right subtree too. -
We can construct the left subtree and right subtree and connect it with the root node and we are done. Now, how do we construct the left and right subtree. We can do using the recursion method and create 3 variables to record the subtree’s inorder and preorder array’s range:
preStartto record the start index of thepreorderarray,inStartandinEndto record the start and ending index of theinorderarray. We don’t needpreEndbecause both array should have the same length. -
Initially,
preStartis 1,inStartis 4,inEndis 3. Now, the left subtree’spreStartis 2,inStartis 4 andinEndis 2; the right subtree’spreStartis also 2,inStartis 5,inEndis 3. We can recursivly using the above method to find out the range of left and right subtree, and connect it with the root recursivly. -
The base case is
preStartis greater thanpreorder’s length andinStartis greater thaninEnd.
Solution
1 | |