Skip to content

Commit 26caa33

Browse files
Merge pull request youngyangyang04#1157 from xiaofei-2020/tree32
添加(0669.修剪二叉搜索树.md):增加typescript版本
2 parents 25c6817 + 551506b commit 26caa33

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

problems/0669.修剪二叉搜索树.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,56 @@ var trimBST = function (root,low,high) {
405405
}
406406
```
407407

408+
## TypeScript
409+
410+
> 递归法
411+
412+
```typescript
413+
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
414+
if (root === null) return null;
415+
if (root.val < low) {
416+
return trimBST(root.right, low, high);
417+
}
418+
if (root.val > high) {
419+
return trimBST(root.left, low, high);
420+
}
421+
root.left = trimBST(root.left, low, high);
422+
root.right = trimBST(root.right, low, high);
423+
return root;
424+
};
425+
```
426+
427+
> 迭代法
428+
429+
```typescript
430+
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
431+
while (root !== null && (root.val < low || root.val > high)) {
432+
if (root.val < low) {
433+
root = root.right;
434+
} else if (root.val > high) {
435+
root = root.left;
436+
}
437+
}
438+
let curNode: TreeNode | null = root;
439+
while (curNode !== null) {
440+
while (curNode.left !== null && curNode.left.val < low) {
441+
curNode.left = curNode.left.right;
442+
}
443+
curNode = curNode.left;
444+
}
445+
curNode = root;
446+
while (curNode !== null) {
447+
while (curNode.right !== null && curNode.right.val > high) {
448+
curNode.right = curNode.right.left;
449+
}
450+
curNode = curNode.right;
451+
}
452+
return root;
453+
};
454+
```
455+
456+
457+
408458

409459
-----------------------
410460
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)