【剑指offer】面试题7:重建二叉树

  • 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
  • 思路:根据先序遍历结果找到根结点root,根据root在中序遍历中的位置确定左右子树的大小,并将其左右子树的两种遍历提取出来进行递归。
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        //采用递归的思想

        if(pre.length<=0||pre.length!=in.length) {
            return null;
        }

        TreeNode root = new TreeNode(pre[0]);

        if(pre.length!=1) {
            //将pre和in转换为ArrayList,方便操作
            ArrayList<Integer> preList = new ArrayList<>();
            ArrayList<Integer> inList = new ArrayList<>();
            for(int i : pre) {
                preList.add(i);
            }
            for(int i : in) {
                inList.add(i);
            }
            //直接在inList中查找root的位置,确定左右子树所含元素个数
            int index = inList.indexOf(pre[0]);
            int leftLength = index;
            int rightLength = in.length-index-1;

            //将ArrayList划分并进行递归调用

            //左子树
            Integer[] preLeft = new Integer[leftLength];
            preList.subList(1,1+leftLength).toArray(preLeft);
            Integer[] inLeft = new Integer[leftLength];
            inList.subList(0,index).toArray(inLeft);
            root.left = reConstructBinaryTree(Arrays.stream(preLeft).mapToInt(Integer::valueOf).toArray(),Arrays.stream(inLeft).mapToInt(Integer::valueOf).toArray());
            //右子树
            Integer[] preRight = new Integer[rightLength];
            preList.subList(1+leftLength,pre.length).toArray(preRight);
            Integer[] inRight = new Integer[rightLength];
            inList.subList(index+1,in.length).toArray(inRight);
            root.right = reConstructBinaryTree(Arrays.stream(preRight).mapToInt(Integer::valueOf).toArray(),Arrays.stream(inRight).mapToInt(Integer::valueOf).toArray());
        }

        return root;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值