Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Solution:
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 TreeNode root = buildTreeRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1); 13 return root; 14 } 15 16 public TreeNode buildTreeRecur(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE){ 17 if (preS>preE) return null; 18 if (preS==preE){ 19 TreeNode leaf = new TreeNode(preorder[preS]); 20 return leaf; 21 } 22 23 int rootVal = preorder[preS]; 24 int index = inS; 25 for (int i=inS;i<=inE;i++) 26 if (inorder[i]==rootVal){ 27 index = i; 28 break; 29 } 30 31 int leftLen = index-inS; 32 int rightLen = inE - index; 33 34 TreeNode leftChild = buildTreeRecur(preorder,inorder,preS+1,preS+leftLen,inS,index-1); 35 TreeNode rightChild = buildTreeRecur(preorder,inorder,preE-rightLen+1,preE,index+1,inE); 36 TreeNode root = new TreeNode(rootVal); 37 root.left = leftChild; 38 root.right= rightChild; 39 return root; 40 } 41 42 }