mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
提交 《从前序与中序遍历序列构造二叉树》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)
|
||||
|
Reference in New Issue
Block a user