@@ -518,6 +518,70 @@ var deleteNode = function (root, key) {
518518}
519519```
520520
521+ ## TypeScript
522+
523+ > 递归法:
524+
525+ ```typescript
526+ function deleteNode (root: TreeNode | null, key: number): TreeNode | null {
527+ if (root === null) return null;
528+ if (root.val === key) {
529+ if (root.left === null && root.right === null) return null;
530+ if (root.left === null) return root.right;
531+ if (root.right === null) return root.left;
532+ let curNode: TreeNode = root.right;
533+ while (curNode.left !== null) {
534+ curNode = curNode.left;
535+ }
536+ curNode.left = root.left;
537+ return root.right;
538+ }
539+ if (root.val > key) root.left = deleteNode(root.left, key);
540+ if (root.val < key) root.right = deleteNode(root.right, key);
541+ return root;
542+ };
543+ ```
544+
545+ > 迭代法:
546+
547+ ```typescript
548+ function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
549+ function removeTargetNode(root: TreeNode): TreeNode | null {
550+ if (root.left === null && root.right === null) return null;
551+ if (root.right === null) return root.left;
552+ if (root.left === null) return root.right;
553+ let curNode: TreeNode | null = root.right;
554+ while (curNode.left !== null) {
555+ curNode = curNode.left;
556+ }
557+ curNode.left = root.left;
558+ return root.right;
559+ }
560+ let preNode: TreeNode | null = null,
561+ curNode: TreeNode | null = root;
562+ while (curNode !== null) {
563+ if (curNode.val === key) break;
564+ preNode = curNode;
565+ if (curNode.val > key) {
566+ curNode = curNode.left;
567+ } else {
568+ curNode = curNode.right;
569+ }
570+ }
571+ if (curNode === null) return root;
572+ if (preNode === null) {
573+ // 删除头节点
574+ return removeTargetNode(curNode);
575+ }
576+ if (preNode.val > key) {
577+ preNode.left = removeTargetNode(curNode);
578+ } else {
579+ preNode.right = removeTargetNode(curNode);
580+ }
581+ return root;
582+ };
583+ ```
584+
521585
522586
523587-----------------------
0 commit comments