imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | use leetcode\util\TreeNode; |
||
| 8 | |||
| 9 | class InsertIntoABinarySearchTree |
||
| 10 | { |
||
| 11 | public static function insertIntoBST(?TreeNode $root, int $val): TreeNode |
||
| 12 | { |
||
| 13 | if (!$root) { |
||
| 14 | return $val ? new TreeNode($val) : new TreeNode(); |
||
| 15 | } |
||
| 16 | |||
| 17 | if ($root->val > $val) { |
||
| 18 | $root->left = self::insertIntoBST($root->left, $val); |
||
| 19 | } |
||
| 20 | if ($root->val < $val) { |
||
| 21 | $root->right = self::insertIntoBST($root->right, $val); |
||
| 22 | } |
||
| 23 | |||
| 24 | return $root; |
||
| 25 | } |
||
| 26 | |||
| 27 | public static function insertIntoBST2(?TreeNode $root, int $val): TreeNode |
||
| 28 | { |
||
| 29 | $curr = $root; |
||
| 30 | while ($curr instanceof TreeNode) { |
||
| 31 | if ($curr->val < $val) { |
||
| 32 | if (!$curr->right) { |
||
| 33 | $curr->right = new TreeNode($val); |
||
| 34 | return $root; |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 35 | } else { |
||
| 36 | $curr = $curr->right; |
||
| 37 | } |
||
| 38 | } |
||
| 39 | if ($curr->val > $val) { |
||
| 40 | if (!$curr->left) { |
||
| 41 | $curr->left = new TreeNode($val); |
||
| 42 | return $root; |
||
|
0 ignored issues
–
show
|
|||
| 43 | } else { |
||
| 44 | $curr = $curr->left; |
||
| 45 | } |
||
| 46 | } |
||
| 47 | } |
||
| 48 | |||
| 49 | return new TreeNode($val); |
||
| 50 | } |
||
| 51 | } |
||
| 52 |