提交 《从前序与中序遍历序列构造二叉树》JavaScript版本的代码

This commit is contained in:
kok-s0s
2021-06-16 09:39:16 +08:00
parent 3461b91704
commit a7d9d7aa23

View File

@ -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)