Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode buildTree(int[] preorder, int[] inorder) { 12 int length = inorder.length; 13 return buildTreeHelp(preorder,inorder,0,length - 1, 0, length - 1); 14 } 15 16 public TreeNode buildTreeHelp(int[] preorder, int[] inorder, int pstart, int pend, int istart,int iend){ 17 TreeNode root = null; 18 if(istart <= iend){ 19 root = new TreeNode(preorder[pstart]); 20 int rootPosition = istart; 21 int newpend = pstart; 22 for(int i = istart; i <= iend; ++i){ 23 if(inorder[i] == preorder[pstart]){ 24 rootPosition = i; 25 break; 26 } 27 else 28 ++newpend; 29 } 30 root.left = buildTreeHelp(preorder, inorder, pstart + 1, newpend, istart, rootPosition - 1); 31 root.right = buildTreeHelp(preorder, inorder, newpend + 1, pend, rootPosition + 1, iend); 32 } 33 return root; 34 } 35 }