Construct Binary Tree from Preorder and Inorder Traversal
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder, inorder,0,0,inorder.length-1);
}
public TreeNode buildTree(int[] preorder, int[] inorder, int p, int l, int h){
if(l>h) return null;
TreeNode root= new TreeNode(preorder[p]);
int i;
for(i=l;i<=h;i++){
if(inorder[i]==preorder[p])
break;
}
root.left=buildTree(preorder, inorder,p+1,l,i-1);
root.right=buildTree(preorder, inorder,p+1+i-l,i+1,h);
return root;
}
}
Last updated
Was this helpful?