重要的事情说三遍!!!
递归太难了!!!递归太难了!!!递归太难了!!!
我还只是个新手啊(小声哔哔)
不说了,直接抄答案(来自牛客网@我去个地方啊)
不过代码都是我自己敲的啊,毕竟还是想要理解一下递归到底怎么用(虽然还是不会用)。敲完自己又测试了一下,结果完全正确,递归真是太厉害了!!!
public class Solution {
//重构二叉树
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0) {
return null;
}
int rootVal = pre[0];
if(pre.length == 1) {
return new TreeNode(rootVal);
}
//前序遍历的第一个值是树的根节点
//遍历中序遍历结果的数组,找到pre[0]相同数值的元素所在的位置,划分成两半
TreeNode root = new TreeNode(rootVal);
int middle = 0;
for(int i=0; i<in.length; i++) {
if(in[i] == pre[0]) {
middle = i;
break;
}
}
//将确定好的左右子树作为新数组,自身调用,构建子树
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1, middle+1),Arrays.copyOfRange(in, 0, middle));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, middle+1, pre.length),Arrays.copyOfRange(in, middle+1, in.length));
return root;
}
//先序遍历
public void preOut(TreeNode root) {
if(root!=null) {
System.out.print(root.val+" ");
preOut(root.left);
preOut(root.right);
}
}
//中序遍历
public void inOut(TreeNode root) {
if(root!=null) {
inOut(root.left);
System.out.print(root.val+" ");
inOut(root.right);
}
}
//后序遍历
public void afterOut(TreeNode root) {
if(root!=null) {
afterOut(root.left);
afterOut(root.right);
System.out.print(root.val+" ");
}
}
}
我就厚着脸选择“原创”了啊