【剑指offer系列】-07重建二叉树(关键字:前序、后序、递归)

在这里插入图片描述

题目:

根据给定的中序、前序结果,确定唯一的树

public class Main7
{
    public static void main(String[] args)
    {
        int[] pre = {1,2,4,7,3,5,6,8};
        int[] mid = {4,7,2,1,5,3,8,6};
        TreeNode root = rebuildTree(pre, 0, pre.length - 1, mid, 0, mid.length - 1);
        prePrint(root);//前序遍历一下子
    }

    private static TreeNode rebuildTree(int[] pre, int preL, int preR, int[] mid, int midL, int midR)
    {
        if (pre.length != mid.length || pre == null || mid == null || pre.length == 0 || mid.length == 0)return null;
        if (preR < preL)return null;
        //1.找到当前根节点,以及根节点在中序中的位置,方便求左右子节点
        TreeNode root = new TreeNode(pre[preL]);
        int i = 0;
        for (i = midL; i < mid.length; i++)
        {
            if (root.val == mid[i])break;
        }
        //2.当前根节点的左子节点
        root.left = rebuildTree(pre, preL+1, preL+(i-midL),mid ,midL,i-1);
        //3.右子节点
        root.right = rebuildTree(pre,preL+(i-midL)+1 ,preR ,mid , i+1,midR );
        return root;
    }

    private static void prePrint(TreeNode root)
    {
        if (root == null)return;
        System.out.print(root.val+" ");
        prePrint(root.left);
        prePrint(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/107802300
今日推荐