【数据结构】根据前序遍历与中序遍历重建树

  直接冲代码

package algorithm_tree;

import java.util.Arrays;

/**
 * @Author: xc
 * @Date: 2019/11/12 20:26
 * @Description:
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *
 *   TreeNode(int x) {
 *       val = x;
 *   }
 *}
 **/
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {

//        List<Object> preList = Arrays.stream(pre).boxed().collect(Collectors.toList());
//        List<Object> inList = Arrays.stream(in).boxed().collect(Collectors.toList());
//        int firstIndex = 0;
//        for(int i = 0;i<inList.size();i++){
//            if (preList.get(0) ==inList.get(i) ){
//                firstIndex = i;
//                break;
//            }
//        }
//        List left = inList.subList(0,firstIndex);
//        List right = inList.subList(firstIndex+1,inList.size());
//        preList.remove(0);
//        TreeNode node = new TreeNode((Integer)inList.get(firstIndex));
//        /*遍历左子树*/
//        TreeNode temp = node;
//        while(!left.isEmpty()){
//
//        }
//        /*遍历右子树*/
//        temp = node;
//        while(!right.isEmpty()){
//
//        }
        /**
         * 重建树,根据原理,从前序遍历的第一个元素值在中序遍历中的值,然后划分左右子树
         * 例如:前序遍历序列{1,2,4,7,3,5,6,8} 中序遍历序列{4,7,2,1,5,3,8,6}。
         * 那么第一个根节点就是1,中序遍历得到左右子树数组{4,7,2},{5,3,8,6}
         *                 1
         *            /         \
         *        {4,7,2}   {5,3,8,6}
         *  之后再在子树数组中找到根节点以及他的左右子树
         *  前序中的1已经用掉了,下一位是2,那么得到{4,7},{}为2的左右子树数组
         *                 1
         *            /         \
         *          2       {5,3,8,6}
         *       /     \
         *    {4,7}   NULL
         *    如此直到左右子树数组为空即遍历完了
         * 上面注释的方法在遍历左子树和右子树时要不断地创建新的左右子数组,而且需要不断地用到while(子树数组不为空)这个条件
         * 于是想到递归*/
        if (pre.length==0 || in.length==0) return null;
        TreeNode rootNode = new TreeNode(pre[0]);

        for (int i = 0;i<in.length;i++){
            if (pre[0] == in[i]){
                /*这个copyOfRange是左闭右开的,要注意取值*/
                int[] left = Arrays.copyOfRange(in,0,i);
                int[] right = Arrays.copyOfRange(in,i+1,in.length);

                rootNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),left);
                rootNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),right);
            }
        }

        return rootNode;



    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值