• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

剑指offer_07_重建二叉树javascript

武飞扬头像
defined_vip
帮助7

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,输入前序遍历序列{1, 2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则重建二叉树并输出它的头节点。二叉树节点的定义如下:

struct BinaryTreeNode {
  int m_nVaule;
  BinaryTreeNode* m_pLeft;
  BinaryTreeNode* m_pRight;
}

题解:分治

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

var buildTree = function(preorder, inorder) {
    if (!preorder.length) return null;
    const rootValue = preorder[0];
    const rootIndex = inorder.indexOf(rootValue);

    const root = new TreeNode(rootValue);
    root.left = buildTree(preorder.slice(1, rootIndex   1), inorder.slice(0, rootIndex))
    root.right = buildTree(preorder.slice(rootIndex   1), inorder.slice(rootIndex   1))
    
    return root
    
};

复杂度分析

  • 时间复杂度:O(n),其中 n 是树中的节点个数。
  • 空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h<n,所以总空间复杂度为 O(n)。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhcjij
系列文章
更多 icon
同类精品
更多 icon
继续加载