Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {//The preorder and inorder traversals for the binary tree above are: /*preorder = {7,10,4,3,1,2,8,11} inorder = {4,10,3,1,7,11,8,2} The first node in preorder alwasy the RO OT of the tree. We can break the tree like:1st Round:preorder: {7}, {10,4,3,1}, {2,8,11} inorder: {4,10,3,1}, {7}, {11, 8,2} can be found, a traversal can be an array of two, corresponding to the Zuozi set and the right subtree set using the preorder array positioning with the node, using the Inorder array sub-tree. Key points: 1 Locating the root node of each Layer 2 calculate the offset note the definition of the Gettree function*/ PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { if(preorder.length!=inorder.length| | preorder.length==0)return NULL; returnGettree (preorder,0,preorder.length-1,inorder,0,inorder.length-1); } TreeNode Gettree (int[] Preorder,intLEFT1,intRIGHT1,int[] inorder,intLEFT2,intright2) { if(LEFT1>RIGHT1)return NULL; if(LEFT2>RIGHT2)return NULL; inttemp=PREORDER[LEFT1]; TreeNode node=NewTreeNode (temp); intindex=left2; for(; index<=right2;index++){ if(inorder[index]==temp) Break; } intlen=index-left2; Node.left=gettree (preorder,left1+1,left1+len,inorder,left2,index-1); Node.right=gettree (preorder,left1+len+1,right1,inorder,index+1, right2); returnnode; }}
[Leedcode 106] Construct Binary Tree from preorder and inorder traversal