@@ -405,6 +405,56 @@ var trimBST = function (root,low,high) {
405
405
}
406
406
```
407
407
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
+
408
458
409
459
-----------------------
410
460
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments