解题思路:pre的第一个节点永远是根节点,在vin中找到根节点的位置,位置左边都是根节点的左子树,位置右边都是根节点的右子树,然后递归每个节点。时间复杂度O(N),空间复杂度O(N)。
import java.util.*;
import java.util.stream.Collectors;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre, int [] vin) {
if (pre.length == 0 || vin.length == 0) {
return null;
}
//将数组转成list
List<Integer> list1 = Arrays.stream(pre).boxed().collect(Collectors.toList());
List<Integer> list2 = Arrays.stream(vin).boxed().collect(Collectors.toList());
return reConstructBinaryTree2(list1, list2);
}
private TreeNode reConstructBinaryTree2( List<Integer> list1,
List<Integer> list2) {
if (list1.size() == 0) {
return null;
}
TreeNode root = new TreeNode(list1.get(0));
int index = list2.indexOf(list1.get(0));
root.left = reConstructBinaryTree2(list1.subList(1, index + 1), list2.subList(0,
index));
root.right = reConstructBinaryTree2(list1.subList(index + 1, list1.size()),
list2.subList(index + 1, list2.size()));
return root;
}
}
方法二:直接使用递归,时间复杂度O(N),空间复杂度O(N)。
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre, int [] vin) {
if (pre.length == 0 || vin.length == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < pre.length; i++) {
if (vin[i] == pre[0]) {
//copyOfRange包括左不包括右
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1),
Arrays.copyOfRange(vin, 0, i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length),
Arrays.copyOfRange(vin, i + 1, vin.length));
break;
}
}
return root;
}
}