java前序遍历&中序遍历还原二叉树。Arrays.copyOfRange()方法与System.arraycopy()方法

根据给定的前序遍历和中序遍历序列,本文介绍了如何重建二叉树。在实现过程中,遇到了Arrays.copyOfRange()方法在特定IDE中不支持的问题,通过替换为System.arraycopy()方法解决了问题。
摘要由CSDN通过智能技术生成

菜鸟发现了一个题目,还原二叉树的。
题目
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

众所周知,前序+中序|中序+后序|中序+层次 是可以唯一确定二叉树的。
根据题目中的例子,菜鸟在纸上把他们写了下来。

前序遍历序列pre={1,2,4,7,3,5,6,8}
中序遍历序列in={4,7,2,1,5,3,8,6},

按照步骤来说

  1. 确定根节点在pre中的位置0,建立根节点root并赋值。
  2. 找出中序遍历也就是in序列中的根节点角标index
  3. 根据index,利用Array.copyOfRange()方法分别把in中的左右子树和pre中的左右子树抄为4个数组
  4. 利用递归,输入这4个数组,然后把根节点贴在root的左右子树上。
  5. 完成。

然后,菜鸟真的这么做了。利用了Array.copyOfRange()方法复制子树数组。

public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length==0){return  null;}
        int the_v=pre[0];
        System.out.println(pre[0]);
        TreeNode root=new TreeNode(the_v);//建立根节点
        int root_index=in_find(in, pre[0]);//找到中序中的根节点角标

         int copy_in_left[]=new int[root_index]; ;
         System.arraycopy(in, 0,copy_in_left,0, root_index);//Arrays.copyOfRange(in, 0, root_index);
         int copy_pre_left[]=new int[root_index];
        System.arraycopy(pre, 1,copy_pre_left,0, root_index);// Arrays.copyOfRange(pre, 1, 1+root_index);
         root.left=reConstructBinaryTree(copy_pre_left, copy_in_left);

         int copy_in_right[]=new int[in.length-1-root_index];
        System.arraycopy(in, root_index+1, copy_in_right, 0, in.length-1-root_index);//Arrays.copyOfRange(in, root_index+1, in.length);
         int copy_pre_right[] =new int[in.length-1-root_index];;
         System.arraycopy(pre, root_index+1, copy_pre_right, 0, in.length-1-root_index);//Arrays.copyOfRange(pre, 1+root_index, pre.length);
         root.right=reConstructBinaryTree(copy_pre_right, copy_in_right);

         return root;


    }

菜鸟发现,注释中的Arrays.copyOfRange()方法能够在本地跑成功,但是在试题的IDE中怎么都出 4个ERROR: can not find symbol;
操了都,怎么找都找不出错误,代码各种改,原来在线服务器的IDE不支持Arrays。换了个System.arraycopy()方法就立马成功了。

1.Arrays.copyOfRange方法
int[] 目标数组=Arrays.copyOfRange(内容数组int[] content,包括的起始位置int a,不包括的结束位置int b);

2.System.arraycopy()方法
首先,要确定目标数组的长度并指定引用变量

int[] target=new int[length];

然后,就要使用方法了。

System.arraycopy(int[] content,int content_start_i, int[] target,int target_start_i, int the_copylength);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值