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

    你可能感兴趣的文章
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>