二叉树---从中序与后序遍历序列构造二叉树

题目:给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

思路:递归法。

第一步:确定参数与返回值。参数为中序数组,数组起始下标,终止下标,后序数组,数组起始下标,终止下标,返回值为树

第二步:确定终止条件。中序数组起始下标>=终止下标时说明划分完毕

第三步:确定单层递归逻辑。

1.如果数组大小为0,说明为空节点

2.如果数组大小不为0,后序遍历数组的最后一个元素是树的根节点

3.找到后序遍历数组的最后一个元素在中序遍历数组中的位置,作为切割点

4.切割中序数组,切割点前的值构成左子树,切割点后的值构成右子树

5.切割后序数组,切成后序左数组,后序右数组

6.递归处理左数组与右数组

代码:

   Map<Integer,Integer> map=new HashMap<>();//方便根据数值找数组下标
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        //构造中序数组的map
        for(int i=0;i<inorder.length;i++){
            map.put(inorder[i],i);
        }
        return findNode(inorder,0,inorder.length,postorder,0,postorder.length);
    }
    public TreeNode findNode(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
        //分割的数组是前闭后开
        //1.如果数组大小为0,说明为空节点
        if(inBegin>=inEnd||postBegin>=postEnd) return null;

        //2.如果数组大小不为0,后序遍历数组的最后一个元素是树的根节点
        int rootValue=postorder[postEnd-1];
        TreeNode root=new TreeNode(rootValue);

        //3.找到后序遍历数组的最后一个元素在中序遍历数组中的位置,作为切割点
        int rootIndex=map.get(rootValue);

        //4.切割中序数组,切割点前的值构成左子树,切割点后的值构成右子树
        int lenOfLeft=rootIndex-inBegin;//左子树的长度
        //中序数组中左子树的区间为[inBegin,rootIndex),右子树的区间为[rootIndex+1,inEnd)

        //5.切割后序数组,切成后序左数组,后序右数组
        //后序数组中左子树的区间为[postBegin,postBegin+lenOfLeft),右子树的区间为[postBegin+lenOfLeft,postEnd-1)
        //6.递归处理左数组与右数组
        root.left=findNode(inorder,inBegin,rootIndex,postorder,postBegin,postBegin+lenOfLeft);
        root.right=findNode(inorder,rootIndex+1,inEnd,postorder,postBegin+lenOfLeft,postEnd-1);
        return root;
    }

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 18:02:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 18:02:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 18:02:02       45 阅读
  4. Python语言-面向对象

    2024-07-20 18:02:02       55 阅读

热门阅读

  1. 冒泡排序代码

    2024-07-20 18:02:02       18 阅读
  2. qt log 输出为文件,每分钟换一个log文件

    2024-07-20 18:02:02       15 阅读
  3. Docker 运维常用命令及问题案例

    2024-07-20 18:02:02       15 阅读
  4. 从零开始!Jupyter Notebook的安装教程

    2024-07-20 18:02:02       18 阅读
  5. HttpHeaders类详解,这一篇就够了

    2024-07-20 18:02:02       18 阅读
  6. WPF中UI元素继承关系

    2024-07-20 18:02:02       22 阅读
  7. Linux复习01

    2024-07-20 18:02:02       16 阅读
  8. 算法刷题笔记 八数码(C++实现)

    2024-07-20 18:02:02       20 阅读
  9. Apollo开发指南

    2024-07-20 18:02:02       19 阅读
  10. Day05 Redis 面试题 下

    2024-07-20 18:02:02       18 阅读
  11. 【鸿蒙学习笔记】UI・页面路由 (@ohos.router)

    2024-07-20 18:02:02       19 阅读