已知前序序列和中序序列重建二叉树

一.解决方法:
在相关的书籍中描述了一个递归的解决方法,其算法思想如下:

1.从前序序列中第一个元素开始,取出一个元素,索引后移一位(preIndex+1)
2.根据选择到的数值创建一个树节点newNode
3.然后查找所选的数值在中序序列中的索引,用inIndex存储
4.递归调用此方法为inIndex之前的数组为中序序列构建一颗子树,将其作为newNode的左子树
5.递归调用此方法为inIndex之后的数组为中序序列构建一颗子树,将其作为newNode的右子树
6.返回newNode

下面我们用实际的例子来推理一遍:

前序遍历{3,9,20,15,7}
中序遍历{9,3,15,20,7}

我们有:
在这里插入图片描述

二.代码实现
在代码实现的过程中我们要注意的点是:
1.当前序数组和中序数组都为空时,我们应该返回null
2.当中序数组只有一位时,该节点的左右孩子都为null

下面是代码实现,注释详细,内含测试方法:

public class ChongJianErChaShu {
    public static void main(String[] args) {
        ChongJianErChaShu test=new ChongJianErChaShu();
        int[] a={1,2};
        int[] b={1,2};
        TreeNode first=test.buildTree(a,b);
        test.Check1(first);
    }

    void Check1(TreeNode first)//前序遍历
    {
        if(first!=null)
        {
            System.out.print(first.val);
            Check1(first.left);
            Check1((first.right));
        }
    }

    /*
     重建二叉树
     */
    int preIndex=0;//全局变量,初始化前序索引
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        //首先检查两个序列的长度,如果一个为零,则返回null
        if (preorder.length==0||inorder.length==0)
        {
            return null;
        }
        //然后以前序序列的preIndex索引上的数新建一个节点
        TreeNode newNode=new TreeNode(preorder[preIndex]);
        int inIndex=-1;//初始化中序序列索引

        //找到前序数值和中序数值相同的索引赋给inIndex
        for(int i=0;i<inorder.length;i++)
        {
            if(inorder[i]==preorder[preIndex]) {
                inIndex = i;
                break;
            }
        }
        preIndex++;//前序索引后移一位
        //如果中序索引的第一位就是前序索引的数值且中序子序列只有一个,则说明该节点孩子节点都为null
        if(inIndex==0&&inorder.length==1)
        {
            newNode.left=null;
            newNode.right=null;

            return newNode;
        }
        //创建左子树序列数组并将该数值前面的数赋给新数组
        int[] behindInorder=new int[inIndex];
        for(int i=0;i<inIndex;i++)
        {
            behindInorder[i]=inorder[i];
        }
       //创建右子树序列数组并将该数值前面的数赋给新数组
        int[] afterInorder=new int[inorder.length-1-inIndex];
        for(int i=0;i<inorder.length-1-inIndex;i++)
        {
            afterInorder[i]=inorder[inIndex+1+i];

        }
        //递归调用创建
        newNode.left=buildTree(preorder,behindInorder);
        newNode.right=buildTree(preorder,afterInorder);

        return newNode;

    }
}

  class TreeNode {
     int val;
     TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员小牧之

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

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

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

打赏作者

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

抵扣说明:

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

余额充值