分别用两个指针指向开头和结束位置即可。注意下边的两个指针指向的数组范围是包括左边界,不包括右边界。
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return dfs(preorder, 0, preorder.length, inorder, 0, inorder.length);
}
private TreeNode dfs(int[] preorder, int p_start, int p_end, int[] inorder, int i_start, int i_end) {
if (p_start == p_end) {
return null;
}
int root_val = preorder[p_start];
TreeNode root = new TreeNode(root_val);
int i_root_index = 0;
for (int i = i_start; i < i_end; i++) {
if (root_val == inorder[i]) {
i_root_index = i;
break;
}
}
int leftNum = i_root_index - i_start;
root.left = dfs(preorder, p_start + 1, p_start + leftNum + 1, inorder, i_start, i_root_index);
root.right = dfs(preorder, p_start + leftNum + 1, p_end, inorder, i_root_index + 1, i_end);
return root;
}
}
|