After the split, the length is equal, that is, the parameter is troublesome, P, the starting point of the first order, the end and start of the IB and IE requirements.
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 return bulid(preorder,inorder, 0, 0,inorder.length-1);// p start of prorder ,ib start of inorder ,ie end of inorder ;13 14 }15 16 /**17 * Definition for binary tree18 * public class TreeNode {19 * int val;20 * TreeNode left;21 * TreeNode right;22 * TreeNode(int x) { val = x; }23 * }24 */25 26 public TreeNode bulid(int[] preorder,int[] inorder,int p,int ib,int ie)27 {28 if(ib>ie) return null;29 int i; //split point30 for(i=ib;i<=ie;i++)31 {32 if(inorder[i]==preorder[p]) break;33 }34 TreeNode root=new TreeNode(preorder[p]);35 root.left= bulid(preorder,inorder,p+1,ib,i-1);36 root.right=bulid(preorder,inorder,p+i-ib+1,i+1,ie);//37 38 39 40 41 return root;42 43 }44 }
/**
* Definition for Binary Tree
* Public class treenode {
* Int val;
* Treenode left;
* Treenode right;
* Treenode (int x) {val = x ;}
*}
*/
Public class solution {
Public treenode buildtree (INT [] inorder, int [] postorder ){
Return bulid (inorder, postorder, postorder. Length-1, 0, inorder. Length-1 );
}
Public treenode bulid (INT [] In, int [] POs, int P, int IB, int IE)
{
If (ib> IE) return NULL;
Int I;
For (I = Ib; I <= ie; I ++)
{
If (Pos [p] = in [I]) break;
}
Treenode root = new treenode (Pos [p]);
Root. Right = bulid (in, POs, P-1, I + 1, ie );
Root. Left = bulid (in, POs, p-ie + I-1, IB, I-1 );
Return root;
}
}