java实现:
package leetcode;
import java.util.ArrayList;
public class TreeBuild {
public static ArrayList list = new ArrayList();
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
TreeNode root = buildBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
private static TreeNode buildBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
if (startPre > endPre || startIn > endIn) {
return null;
}
TreeNode root = new TreeNode(pre[startPre]);
for (int i = startIn; i <= endIn; i++)
if (in[i] == pre[startPre]) {
root.setLeft(buildBinaryTree(pre, startPre + 1, startPre + i - startIn, in, startIn, i - 1));
root.setRight(buildBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn));
break;
}
return root;
}
/*
* 递归先序遍历
*/
public static void preOrder(TreeNode treeNode) {
list.add(treeNode.getData());
if (treeNode.getLeft() != null) {
preOrder(treeNode.getLeft());
}
if (treeNode.getRight() != null) {
preOrder(treeNode.getRight());
}
}
public static void main(String[] args) {
int[] pre = {输入};
int[] in = {输入};
preOrder(reConstructBinaryTree(pre, in));
for (Object a : list){
System.out.println(a);
}
}
}
转自:https://blog.csdn.net/weixin_42805929/article/details/82946080
也可以用
java自带方法Arrays.copyOfRange()来对数组进行拷贝