mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -520,5 +520,71 @@ var insertIntoBST = function (root, val) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## TypeScript
|
||||||
|
|
||||||
|
> 递归-有返回值
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||||
|
if (root === null) return new TreeNode(val);
|
||||||
|
if (root.val > val) {
|
||||||
|
root.left = insertIntoBST(root.left, val);
|
||||||
|
} else {
|
||||||
|
root.right = insertIntoBST(root.right, val);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 递归-无返回值
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||||
|
if (root === null) return new TreeNode(val);
|
||||||
|
function recur(root: TreeNode | null, val: number) {
|
||||||
|
if (root === null) {
|
||||||
|
if (parentNode.val > val) {
|
||||||
|
parentNode.left = new TreeNode(val);
|
||||||
|
} else {
|
||||||
|
parentNode.right = new TreeNode(val);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
parentNode = root;
|
||||||
|
if (root.val > val) recur(root.left, val);
|
||||||
|
if (root.val < val) recur(root.right, val);
|
||||||
|
}
|
||||||
|
let parentNode: TreeNode = root;
|
||||||
|
recur(root, val);
|
||||||
|
return root;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||||
|
if (root === null) return new TreeNode(val);
|
||||||
|
let curNode: TreeNode | null = root;
|
||||||
|
let parentNode: TreeNode = root;
|
||||||
|
while (curNode !== null) {
|
||||||
|
parentNode = curNode;
|
||||||
|
if (curNode.val > val) {
|
||||||
|
curNode = curNode.left
|
||||||
|
} else {
|
||||||
|
curNode = curNode.right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (parentNode.val > val) {
|
||||||
|
parentNode.left = new TreeNode(val);
|
||||||
|
} else {
|
||||||
|
parentNode.right = new TreeNode(val);
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user