mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
提供JavaScript版本的《二叉搜索树中的插入操作》
This commit is contained in:
@ -320,7 +320,84 @@ var insertIntoBST = function (root, val) {
|
||||
};
|
||||
```
|
||||
|
||||
> 无返回值的递归
|
||||
|
||||
```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) {
|
||||
let parent = new TreeNode(0);
|
||||
const preOrder = (cur, val) => {
|
||||
if (cur === null) {
|
||||
let node = new TreeNode(val);
|
||||
if (parent.val > val)
|
||||
parent.left = node;
|
||||
else
|
||||
parent.right = node;
|
||||
return;
|
||||
}
|
||||
parent = cur;
|
||||
if (cur.val > val)
|
||||
preOrder(cur.left, val);
|
||||
if (cur.val < val)
|
||||
preOrder(cur.right, val);
|
||||
}
|
||||
if (root === null)
|
||||
root = new TreeNode(val);
|
||||
preOrder(root, val);
|
||||
return root;
|
||||
};
|
||||
```
|
||||
|
||||
> 迭代
|
||||
|
||||
```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) {
|
||||
if (root === null) {
|
||||
root = new TreeNode(val);
|
||||
} else {
|
||||
let parent = new TreeNode(0);
|
||||
let cur = root;
|
||||
while (cur) {
|
||||
parent = cur;
|
||||
if (cur.val > val)
|
||||
cur = cur.left;
|
||||
else
|
||||
cur = cur.right;
|
||||
}
|
||||
let node = new TreeNode(val);
|
||||
if (parent.val > val)
|
||||
parent.left = node;
|
||||
else
|
||||
parent.right = node;
|
||||
}
|
||||
return root;
|
||||
};
|
||||
```
|
||||
|
||||
-----------------------
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
|
Reference in New Issue
Block a user