[JavaScript 刷题] 树 - 从前序与中序遍历序列构造二叉树, leetcode 105

[JavaScript 刷题] 树 - 从前序与中序遍历序列构造二叉树, leetcode 105

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:

题目

如下:

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:

[3,9,20,15,7]

inorder:

[9,3,15,20,7]

已知 preorder 数组中的第一个值为当前结点(root),inorder 使用 inorder[indexOf(preorder[0])] 可以找到当前结点(root),该值左侧为 root 的左子树,右侧为 root 的右子树,根据这个方法就可以拆分出当前二叉树。

依旧以提供的案例来说:

  1. root 为 3

    左子树调用 buildTree([9], [9,3])

    这里 preorder 的值剔除了当前的 root,所以取值范围为 (0, min]

    右子树调用 buildTree([20,15,7], [15,20,7])

    取值范围为 (mid, ..., arr.length)

  2. buildTree([9], [9,3]) 的结果返回 TreeNode(3)

  3. buildTree([20,15,7], [15,20,7]) 返回 TreeNode(20)

    其左右子树依旧会继续递归调用 buildTree() 去创建新的子节点

使用 JavaScript 解题

// [3,      9,      20,15,7]
// root    left

// [9,      3,      15,20,7]
// left     root

var buildTree = function (preorder, inorder) {
    
    
  if (!preorder.length || !inorder.length) return null;

  const root = new TreeNode(preorder[0]);
  const mid = inorder.indexOf(preorder[0]);

  root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid + 1));
  root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1));

  return root;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125598353