重建二叉树

根据前序遍历和中序遍历结果重建二叉树

思路:

1、前序遍历的第一个数字为原二叉树根节点的值;

2、遍历中序序列,找到根节点位置,根节点左边序列即为左子树所有节点,右边序列即为右子树所有节点;

3、用同样的方法(上面两个步骤)对剩下的小序列进行操作,即一个递归的过程。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W5u5DW0e-1614068592292)(C:\Users\雷歌儿\AppData\Roaming\Typora\typora-user-images\image-20210223094536147.png)]

具体代码

public class TreeNode {
    TreeNode left;
    TreeNode right;
    int value;
    public TreeNode(int value){
        this.value = value;
    }
    //pre:前序序列  in:中序序列
    public static TreeNode reBuild(int[]pre,int[]in){
        if(pre ==null ||in == null){
            return null;
        }
        TreeNode root = reBuildCore(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }

    private static TreeNode reBuildCore(int[]pre,int pStart,int pEnd,int[]in,int iStart,int iEnd) {
        if(pStart>pEnd || iStart > iEnd){
            return null;
        }
        TreeNode root = new TreeNode(pre[pStart]);
        for (int i = iStart; i <= iEnd; i++) {
            if(pre[pStart] == in[i]){
                //边界为前序遍历和中序遍历左子树序列边界
                root.left = reBuildCore(pre,pStart+1,pStart+(i-iStart),in,iStart,i-1);
                //边界为前序遍历和中序遍历右子树序列边界
                root.right = reBuildCore(pre,pStart+(i-iStart)+1,pEnd,in,i+1,iEnd);
            }

        }
        return root;
    }
    //前序遍历
    public static void prePrint(TreeNode head){
        if (head == null) {
            return;
        }
		System.out.print(head.value+" ");
        prePrint(head.left);
        prePrint(head.right);
        
    }
    public static void main(String[] args) {
        int preorder[] = {1, 2, 4, 7, 3, 5, 6, 8};
        int inorder[] = {4, 7, 2, 1, 5, 3, 8, 6};
        TreeNode treeNode = reBuild(preorder, inorder);
        System.out.println(treeNode.value);
        //prePrint(treeNode);

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值