剑指offer_07_重建二叉树【javascript】

56 阅读1分钟

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,输入前序遍历序列{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)。