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
preorder
array, the first element is the root of the tree. We can find this value also in theinorder
array. 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
1
is the first value ofpreorder
, and we can find it in theinorder
array at the third element. So, in theinorder
array, any elements before1
is from the left subtree, which are 4 and 2, and so in thepreorder
array, its next two elements 2 and 4 are from the left subtree too; in theinorder
array, any elements after1
is from the right subtree, which are 5 and 3, and so in thepreorder
array, 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:
preStart
to record the start index of thepreorder
array,inStart
andinEnd
to record the start and ending index of theinorder
array. We don’t needpreEnd
because both array should have the same length. -
Initially,
preStart
is 1,inStart
is 4,inEnd
is 3. Now, the left subtree’spreStart
is 2,inStart
is 4 andinEnd
is 2; the right subtree’spreStart
is also 2,inStart
is 5,inEnd
is 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
preStart
is greater thanpreorder
’s length andinStart
is greater thaninEnd
.
Solution
1 |
|