题目:
题解:
- 前序序列第一个节点为根节点
- 通过根节点拆分中序序列为左中序序列,右中序序列
- 递归遍历
public TreeNode buildTree(int[] preOrder, int[] inOrder) {
return buildTreeByPreOrderAndInOrder(preOrder, 0, preOrder.length, inOrder, 0, inOrder.length);
}
public TreeNode buildTreeByPreOrderAndInOrder(int[] preOrder, int preLeft, int preRight, int[] inOrder, int inLeft, int inRight) {
if (inLeft >= inRight) {
return null;
}
int rootValue = preOrder[preLeft];
int index = findIndexByValue(inOrder, rootValue);
TreeNode root = new TreeNode(rootValue);
root.left = buildTreeByPreOrderAndInOrder(preOrder, preLeft+1, preLeft+(index-inLeft), inOrder, inLeft, index);
root.right = buildTreeByPreOrderAndInOrder(preOrder, preLeft+(index-inLeft)+1, preRight, inOrder, index+1, inRight);
return root;
}
private int findIndexByValue(int[] nums, int targetValue) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == targetValue) {
return i;
}
}
return 0;
}
时间复杂度:O(n)