Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

105. 从前序与中序遍历序列构造二叉树 #32

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

105. 从前序与中序遍历序列构造二叉树 #32

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

105. 从前序与中序遍历序列构造二叉树

Description

Difficulty: 中等

Related Topics: , 数组, 哈希表, 分治, 二叉树

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:

输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]

示例 2:

输入: preorder = [-1], inorder = [-1]
输出: [-1]

提示:

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder 和 inorder 均 无重复 元素
  • inorder 均出现在 preorder
  • preorder 保证 为二叉树的前序遍历序列
  • inorder 保证 为二叉树的中序遍历序列

Solution

Language: JavaScript

/**
 * 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}
 */
// 前序遍历: 根-左-右
// 中序遍历:左-根-右
// 先用前序遍历找根节点,在用根节点去中序遍历确定左右子树
var buildTree = function(preorder, inorder) {
    // 当preorder和inorder均为空的时候说明已经到了空节点
    if (!preorder.length || !inorder.length) return null

    // 创建根节点 -> preorder[0]
    let node = new TreeNode(preorder[0])

    // 找到perorder[0]对应inorder中的位置
    let index = inorder.indexOf(preorder.shift())

    // 左右子树递归
    node.left = buildTree(preorder, inorder.slice(0, index))
    node.right = buildTree(preorder, inorder.slice(index + 1))

    // 返回根节点
    return node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant