Skip to content

106.从中序与后序遍历序列构造二叉树

题解

js
/**
 * 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[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, postorder) {
  if (!inorder.length && !postorder.length) {
    return null;
  }
  const val = postorder[postorder.length - 1];
  const node = new TreeNode(val);
  const mid = inorder.indexOf(val);
  node.left = buildTree(inorder.slice(0, mid), postorder.slice(0, mid));
  node.right = buildTree(
    inorder.slice(mid + 1),
    postorder.slice(mid, postorder.length - 1)
  );
  return node;
};
/**
 * 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[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, postorder) {
  if (!inorder.length && !postorder.length) {
    return null;
  }
  const val = postorder[postorder.length - 1];
  const node = new TreeNode(val);
  const mid = inorder.indexOf(val);
  node.left = buildTree(inorder.slice(0, mid), postorder.slice(0, mid));
  node.right = buildTree(
    inorder.slice(mid + 1),
    postorder.slice(mid, postorder.length - 1)
  );
  return node;
};