提供JavaScript版本的《二叉搜索树中的插入操作》

This commit is contained in:
kok-s0s
2021-06-23 22:15:10 +08:00
parent bf7597facf
commit 826927e6ad

View File

@ -286,6 +286,39 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
} }
``` ```
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 {TreeNode} root
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function (root, val) {
const setInOrder = (root, val) => {
if (root === null) {
let node = new TreeNode(val);
return node;
}
if (root.val > val)
root.left = setInOrder(root.left, val);
else if (root.val < val)
root.right = setInOrder(root.right, val);
return root;
}
return setInOrder(root, val);
};
```