Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
============
Analysis:
Exact the same idea as [leet code] Construct Binary Tree from Inorder and Postorder Traversal, except this time we use preorder array (from left to right) instead of postorder array (from right to left) to determine the current root node and in order array's split point.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
}
public TreeNode helper(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight){
if(preLeft>preRight || inLeft>inRight) return null;
TreeNode currNode = new TreeNode(preorder[preLeft]);
int splitPoint = 0;
for(int i=inLeft; i<=inRight; i++){
if(inorder[i] == currNode.val) splitPoint = i;
}
currNode.left = helper(preorder, preLeft+1, preLeft+(splitPoint-inLeft), inorder, inLeft, splitPoint-1);
currNode.right = helper(preorder, preLeft+(splitPoint-inLeft)+1, preRight, inorder, splitPoint+1, inRight);
return currNode;
}
}