收获的喜悦# Joke - 肚皮舞运动
h*s
1 楼
Given inorder and postorder traversal of a tree, construct the binary tree.
觉得并不难,但是online judge之后,judge small能通过,judge large不通过,报
Runtime Error。下面是我的代码,高人能否分析下问题出在哪儿了。
public static TreeNode buildTree(int[] inorder, int[] postorder) {
// Start typing your Java solution below
// DO NOT write main() function
if(inorder.length==0 && postorder.length==0) return null;
int n = inorder.length;
int root_val = postorder[n-1];
TreeNode root = new TreeNode(root_val);
int index=0;
for(int i=0;i if(inorder[i]==root_val) index=i;
}
int[] inorder_left = new int[]{};
if(index!=0) inorder_left= Arrays.copyOfRange(inorder, 0, index);
int[] inorder_right = new int[]{};
if(index!=n-1) inorder_right = Arrays.copyOfRange(inorder, index+1,
n);
int[] postorder_left = new int[]{};
if(index!=0) postorder_left = Arrays.copyOf(postorder, inorder_left.
length);
int[] postorder_right = new int[]{};
if(index!=n-1) postorder_right = Arrays.copyOfRange(postorder, index
,n-1);
root.left = buildTree(inorder_left,postorder_left);
root.right = buildTree(inorder_right,postorder_right);
return root;
}
觉得并不难,但是online judge之后,judge small能通过,judge large不通过,报
Runtime Error。下面是我的代码,高人能否分析下问题出在哪儿了。
public static TreeNode buildTree(int[] inorder, int[] postorder) {
// Start typing your Java solution below
// DO NOT write main() function
if(inorder.length==0 && postorder.length==0) return null;
int n = inorder.length;
int root_val = postorder[n-1];
TreeNode root = new TreeNode(root_val);
int index=0;
for(int i=0;i
}
int[] inorder_left = new int[]{};
if(index!=0) inorder_left= Arrays.copyOfRange(inorder, 0, index);
int[] inorder_right = new int[]{};
if(index!=n-1) inorder_right = Arrays.copyOfRange(inorder, index+1,
n);
int[] postorder_left = new int[]{};
if(index!=0) postorder_left = Arrays.copyOf(postorder, inorder_left.
length);
int[] postorder_right = new int[]{};
if(index!=n-1) postorder_right = Arrays.copyOfRange(postorder, index
,n-1);
root.left = buildTree(inorder_left,postorder_left);
root.right = buildTree(inorder_right,postorder_right);
return root;
}