C*******a 发帖数: 448 | 1 以下是这道题正确的代码
然而当我想把代码简洁一些,把标有*的4行换成1行:
int i = Arrays.asList(inorder).indexOf(preorder[preL]);
就会报错。谁知道错在哪儿???
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return _buildTree(preorder, 0, preorder.length, inorder, 0, inorder.
length);
}
private TreeNode _buildTree(int[] preorder, int preL, int preR, int[]
inorder, int inL, int inR) {
if (preL >= preR) {return null;}
TreeNode root = new TreeNode(preorder[preL]);
* int i = inL;
* for (; i < inR; i++) {
* if (inorder[i] == preorder[preL]) {break;}
* }
root.left = _buildTree(preorder, preL + 1, preL + 1 + i - inL,
inorder, inL, i);
root.right = _buildTree(preorder, preL + 1 + i - inL, preR, inorder,
i + 1, inR);
return root;
}
} |
|