Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
classSolution {publicTreeNodehelper(int[] inorder,int inStart,int inEnd,int[] preorder,int preStart,int preEnd,HashMap<Integer,Integer> map) {if (preStart > preEnd)returnnull;TreeNode root =newTreeNode(preorder[preStart]);int index =map.get(preorder[preStart]);int leftLength = index - inStart;int rightLength = inEnd - index;root.left=helper(inorder, inStart, index -1, preorder, preStart +1, preStart + leftLength, map);root.right=helper(inorder, index +1, inEnd, preorder, preEnd - rightLength +1, preEnd, map);return root; }publicTreeNodebuildTree(int[] preorder,int[] inorder) {// We can use map because it is given that : duplicates do not exist in the treeHashMap<Integer,Integer> map =newHashMap<>();for (int i =0; i <inorder.length; i++) {map.put(inorder[i], i); }returnhelper(inorder,0,inorder.length-1, preorder,0,preorder.length-1, map); }}