mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #410 from kok-s0s/master
提交 《从前序与中序遍历序列构造二叉树》JavaScript版本的代码
This commit is contained in:
@ -775,6 +775,20 @@ var buildTree = function(inorder, postorder) {
|
||||
};
|
||||
```
|
||||
|
||||
从前序与中序遍历序列构造二叉树
|
||||
|
||||
```javascript
|
||||
var buildTree = function(preorder, inorder) {
|
||||
if(!preorder.length)
|
||||
return null;
|
||||
let root = new TreeNode(preorder[0]);
|
||||
let mid = inorder.findIndex((number) => number === root.val);
|
||||
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
|
||||
root.right = buildTree(preorder.slice(mid + 1, preorder.length), inorder.slice(mid + 1, inorder.length));
|
||||
return root;
|
||||
};
|
||||
```
|
||||
|
||||
-----------------------
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
|
@ -311,6 +311,42 @@ func findMax(nums []int) (index int){
|
||||
}
|
||||
```
|
||||
|
||||
JavaScript版本
|
||||
|
||||
```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[]} nums
|
||||
* @return {TreeNode}
|
||||
*/
|
||||
var constructMaximumBinaryTree = function (nums) {
|
||||
const BuildTree = (arr, left, right) => {
|
||||
if (left > right)
|
||||
return null;
|
||||
let maxValue = -1;
|
||||
let maxIndex = -1;
|
||||
for (let i = left; i <= right; ++i) {
|
||||
if (arr[i] > maxValue) {
|
||||
maxValue = arr[i];
|
||||
maxIndex = i;
|
||||
}
|
||||
}
|
||||
let root = new TreeNode(maxValue);
|
||||
root.left = BuildTree(arr, left, maxIndex - 1);
|
||||
root.right = BuildTree(arr, maxIndex + 1, right);
|
||||
return root;
|
||||
}
|
||||
let root = BuildTree(nums, 0, nums.length - 1);
|
||||
return root;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user