| Total Complexity | 8 |
| Total Lines | 32 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 9 | class DeleteNodeInABinarySearchTree |
||
| 10 | { |
||
| 11 | public static function deleteNode(?TreeNode $root, int $key): ?TreeNode |
||
| 12 | { |
||
| 13 | if (!$root) { |
||
| 14 | return $root; |
||
| 15 | } |
||
| 16 | if ($root->val > $key) { |
||
| 17 | $root->left = self::deleteNode($root->left, $key); |
||
| 18 | } elseif ($root->val < $key) { |
||
| 19 | $root->right = self::deleteNode($root->right, $key); |
||
| 20 | } else { |
||
| 21 | if (!$root->left) { |
||
| 22 | return $root->right ?? new TreeNode(); |
||
| 23 | } |
||
| 24 | if (!$root->right) { |
||
| 25 | return $root->left ?? new TreeNode(); |
||
| 26 | } |
||
| 27 | $node = self::findMinNode($root->right); |
||
| 28 | $root->val = $node->val; |
||
| 29 | $root->right = self::deleteNode($root->right, $node->val); |
||
| 30 | } |
||
| 31 | |||
| 32 | return $root; |
||
| 33 | } |
||
| 34 | |||
| 35 | private static function findMinNode(?TreeNode $node): TreeNode |
||
| 41 | } |
||
| 42 | } |
||
| 43 |