博客
关于我
剑指 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/

    你可能感兴趣的文章
    Python append() 与列表上的 + 运算符,为什么这些会给出不同的结果?
    查看>>
    Python APP自动化测试工具adb与Monkey使用详解
    查看>>
    Python APP自动化测试框架Appium详解
    查看>>
    Python APP自动化测试框架开发实战
    查看>>
    python argparse模块
    查看>>
    Python asyncio库的学习和使用
    查看>>
    Python AttributeError:“dict“对象没有属性“append“
    查看>>
    Python base64和hashlib模块
    查看>>
    python basic programs
    查看>>
    python bert_gen.py 报错Unable to load weights from pytorch checkpoint file for......
    查看>>
    python binascii.Error: Incorrect padding
    查看>>
    Python bool() 函数能否为无效参数引发异常?
    查看>>
    Python C 程序子进程在“for line in iter“处挂起
    查看>>
    Python Celery:自动化测试平台定时任务必备的三方库
    查看>>
    python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令
    查看>>
    Python CONNECT 4 CHECK WIN函数
    查看>>
    python cos,Python cos(90)和cos(270)不是0
    查看>>
    python进阶(4):Python 脚本文件重启自身进程
    查看>>
    python ctypes库中动态链接库加载方式
    查看>>
    python cv2 图像( np array )转 HObject
    查看>>