Учитывая обход дерева по порядку и порядку, построите двоичное дерево. Примечание: вы можете предположить, что дубликаты не существуют в дереве. Пример: Ввод: Inorder: [2, 1, 3] postorder: [2, 3, 1]
Я использовал рекурсию и начал переходить от последнего в postorder и попытался найти индекс в inorder и разделил мое деревосоответственно
public class Solution {
int p;
public TreeNode buildTree(int[] in, int[] post) {
p=in.length-1;
//calling helper to build my tree
return helper(in,post,0,in.length-1);
}
TreeNode helper(int[] in,int[] post,int s,int e)
{
if(s>e) //exit condition
return null;
/*p is initailised by the last index of postorder and i am creating
the root using that, then my p will get decremented for the secondlast
At each step after creating the root, i will find the index of the
element in inorder as all the element left of this index in inorder
will form the left subtree and all the element right of this index in
inorder will form the right subtree
i am not very sure if right subtree should be constructed before left
*/
TreeNode root=new TreeNode(post[p--]); //the point of error
int index=find(in,root.val);
root.right=helper(in,post,index+1,e);
root.left=helper(in,post,s,index-1);
return root;
}
//find the index of postorder[p] in inorder
int find(int[] a,int x)
{
for(int i=0;i<a.length-1;i++)
{
if(a[i]==x)
return i;
}
return 0;
}
}
this is the error i am facing
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Solution.helper(Solution.java:25)
at Solution.helper(Solution.java:27)
at Solution.helper(Solution.java:27)
at Solution.helper(Solution.java:27)
at Solution.buildTree(Solution.java:18)
at Main.main(Main.java:193)