We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Difficulty: 中等
Related Topics: 树, 数组, 哈希表, 分治, 二叉树
给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
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
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 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
105. 从前序与中序遍历序列构造二叉树
Description
Difficulty: 中等
Related Topics: 树, 数组, 哈希表, 分治, 二叉树
给定两个整数数组
preorder
和inorder
,其中preorder
是二叉树的先序遍历,inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。示例 1:
示例 2:
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
和inorder
均 无重复 元素inorder
均出现在preorder
preorder
保证 为二叉树的前序遍历序列inorder
保证 为二叉树的中序遍历序列Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: