java剑指offer:二叉树重构,根据中序和前序遍历的数据重构二叉树

package offer_algorithms;

public class ConstructBT {
    //根据前序和中序构建二叉树
    public static void main(String[] args) {
        int[] pre = new int[]{1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = new int[]{4, 7, 2, 1, 5, 3,6, 8};
        ConstructBT c = new ConstructBT();
        Node t = c.trConstructBT(pre, in);


    }

    /**
     * @param preData 前序遍历数据
     * @param inData  中序遍历数据
     */
    public Node trConstructBT(int[] preData, int[] inData) {
        if (preData == null || inData == null || preData.length == 0 || inData.length == 0) {
            return null;//特殊输入
        }
        if (preData.length == 1 && inData.length == 1) {
            return new Node(preData[0]);
        }
        //根据先序序列获得根结点值
        int root = preData[0];
        Node tree = new Node(root);


        //在中序序列中找到root的位置,然后分开左右子树
        int rootIndex = -1;
        for (int i = 0; i < inData.length; i++) {
            if (inData[i] == root) {
                rootIndex = i;
                break;
            }
        }
        int right_len = inData.length - rootIndex -1;//将中序序列根据root分开
        //此时新的前序,和后序分别放出来了
        int[] left_pre = new int[rootIndex];
        int[] left_in = new int[rootIndex];

        int[] right_pre = new int[right_len];
        int[] right_in = new int[right_len];

        for (int i = 1; i < rootIndex + 1; i++) {
            left_pre[i - 1] = preData[i];
            left_in[i - 1] = inData[i - 1];

        }

        for (int i = rootIndex + 1; i < preData.length; i++) {

            right_pre[i - rootIndex - 1] = preData[i];
            right_in[i - rootIndex - 1] = inData[i];
        }
        tree.left = trConstructBT(left_pre, left_in);
        tree.right = trConstructBT(right_pre, right_in);
        return tree;


    }

    class Node {
        private int data;
        private Node left;
        private Node right;

        public Node(int data) {
            this.data = data;

        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君子慎独_诚意

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值