这是我从预订中获取树的简单代码以及树的符号表示法。
我想使用递归。
但是JAVA说错误:'.class' expected in "here"
。
它与承诺的概念有关吗? 如何避免此错误
public class Main {
public static void main(String args[]){
int[] preorder = new int[] {3, 9, 8, 12, 13};
int[] inorder = new int[] {9, 3, 12, 8, 13};
TreeNode result;
TreeNode root = new TreeNode(preorder[0]);
root.left = new TreeNode(3);
System.out.println(root.left.val);
}
public static TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode root = new TreeNode(preorder[0]);
if (preorder.length==1) return root;
int rootindex=-1;
for (int i=0 ; i<inorder.length ; i++) {
if (inorder[i]==preorder[0]) rootindex = i;
}
int[] leftpre = new int[rootindex];
for (int i=0 ; i<rootindex ; i++ )
leftpre[i] = preorder[i+1];
int[] rightpre = new int[(preorder.length-(1+rootindex))];
for (int i=0 ; i<preorder.length-(1+rootindex) ; i++)
rightpre[i] = preorder[i+1+rootindex];
int[] leftin = new int[rootindex];
for (int i=0 ; i<rootindex ; i++)
leftin[i] = inorder[i];
int[] rightin = new int[(inorder.length-(1+rootindex))];
for (int i=0 ; i<inorder.length-(1+rootindex) ; i++)
rightin[i] = inorder[i+1+rootindex];
TreeNode left = new buildTree(int[] leftpre, int[] leftin); //here
root.left = left;
TreeNode right = new buildTree(int[] rightpre, int[] rightin); // and here
root.right = right;
return root;
}
}