Skip to main content
105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

LZXAbout 1 minLeetCodeMediumHashMapTree

105. Construct Binary Tree from Preorder and Inorder Traversal

題目 連結open in new window

Given two integer arrays preorder and inorder where >preorder is the preorder traversal of a binary tree and >inorder is the inorder traversal of the same tree, >construct and return the binary tree.

翻譯

給定兩個整數數組 preorder 和 inorder ,其中 preorder 是二元樹的前序遍歷, inorder 是二元樹的中序遍歷樹,構造並返回二元樹。

測試資料

Example 1: 範例 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Output: [3,9,20,null,null,15,7]

Example 2: 範例 2:

Input: preorder = [-1], inorder = [-1]

Output: [-1]

解題思路

前中序關係

程式碼

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

// Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
// Output: [3,9,20,null,null,15,7]
class TreeNode {
  constructor(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

var buildTree = function (preorder, inorder) {
  let map = new Map();
  for (let i = 0; i < inorder.length; i++) {
    map.set(inorder[i], i);
  }
  return solve(preorder, inorder, 0, 0, inorder.length - 1, map);
};

var solve = function (preorder, inorder, preStart, inStart, inEnd, map) {
  if (inStart > inEnd || preStart > preorder.length - 1) {
    return null;
  }
  let rootIndex = map.get(preorder[preStart]);
  let node = new TreeNode(preorder[preStart]);

  node.left = solve(
    preorder,
    inorder,
    preStart + 1,
    inStart,
    rootIndex - 1,
    map
  );

  node.right = solve(
    preorder,
    inorder,
    preStart + (rootIndex - inStart) + 1,

    rootIndex + 1,
    inEnd,
    map
  );

  return node;
};

console.log(buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]));