Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
You may assume that duplicates do not exist in the tree.
Example:
Given in-order [1,2,3] and pre-order [2,1,3], return a tree:
2
/ \
1 3
Solution:
As can be seen on above example, we could repeat following steps to obtain a binary tree:
- due to the definition of pre-order, we have the root value is preorder[0] (2)
- use root value to find its index in in-order (1), then we know the left subtree is from 0 to 1 - 1 and right subtree is 1 + 1 to 2 which are inorder[0] (1) and inorder[3] respectively
- based on the length of left and right subtree we can split preorder array into two subtrees
Code:
public class Solution {
public TreeNode buildTree(int[] inorder, int[] preorder) {
return buildTree(preorder, 0, preorder.length - 1, inorder,
0, inorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int pstart, int pend,
int[] inorder, int istart, int iend) {
if (pstart > pend || istart > iend) {
return null;
}
int idx = findIndex(preorder, pstart, pend, inorder[istart]);
TreeNode node = new TreeNode(preorder[idx]);
node.left = buildTree(preorder, pstart, idx - 1, inorder,
istart + 1, idx - pstart + istart);
node.right = buildTree(preorder, idx + 1, pend, inorder,
idx - pstart + istart + 1, iend);
return node;
}
private int findIndex(int[] preorder, int pstart, int pend, int num) {
int i = 0;
for (i = pstart; i <= pend; i++) {
if (preorder[i] == num) {
break;
}
}
return i;
}
}