博客
关于我
剑指 Offer 07. 重建二叉树
阅读量:85 次
发布时间:2019-02-26

本文共 1366 字,大约阅读时间需要 4 分钟。

问题描述

输入某二叉树的前序遍历和中序遍历结果,请重建该二叉树。假设输入的前序遍历和中序遍历结果中都不含重复的数字。例如,给出前序遍历 preorder = [3,9,20,15,7] 和中序遍历 inorder = [9,3,15,20,7],返回如下的二叉树:

3   / \  9   20     / \    15  7

解决思路

树的相关问题通常可以考虑使用递归的方法来解决。递归法通过分治的思想,逐步划分子树,直到找到单个节点为止。

具体来说,我们可以采用以下步骤来重建二叉树:

  • 首先,建立一个映射表,将中序遍历中的节点值与其位置存储起来。这样可以快速找到某个节点在中序遍历中的位置。

  • 然后,通过递归的方式,从前序遍历和中序遍历中依次找到子树的根节点及其左右子树的范围。具体来说:

    • 根节点的值在前序遍历中位于当前范围内的第一个位置。
    • 根节点的位置在中序遍历中确定后,左子树的范围是从左边界到根节点左边的位置,右子树的范围是从根节点右边的位置到右边界。
  • 递归地重建左子树和右子树,直到所有节点都被处理完毕。

  • 代码实现

    import java.util.HashMap;import java.util.Map;class Solution {    Map
    map = new HashMap<>(); int[] preorder; public TreeNode buildTree(int[] preorder, int[] inorder) { this.preorder = preorder; for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return trackck(0, 0, preorder.length - 1); } public TreeNode trackck(int rootPreIndex, int inorderLeft, int inorderRight) { if (inorderLeft > inorderRight) { return null; } TreeNode root = new TreeNode(preorder[rootPreIndex]); int rootInIndex = map.get(preorder[rootPreIndex]); root.left = trackck(rootPreIndex + 1, inorderLeft, rootInIndex - 1); root.right = trackck(rootPreIndex + (rootInIndex - inorderLeft + 1), rootInIndex + 1, inorderRight); return root; }}

    这个方法的核心思想是利用前序遍历和中序遍历的特点,通过递归的方式分割子树,最终重建出原来的二叉树。

    转载地址:http://wxsu.baihongyu.com/

    你可能感兴趣的文章
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>