-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInsertIntoABinarySearchTree.php
51 lines (43 loc) · 1.25 KB
/
InsertIntoABinarySearchTree.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
declare(strict_types=1);
namespace leetcode;
use leetcode\util\TreeNode;
class InsertIntoABinarySearchTree
{
public static function insertIntoBST(?TreeNode $root, int $val): TreeNode
{
if (!$root) {
return $val ? new TreeNode($val) : new TreeNode();
}
if ($root->val > $val) {
$root->left = self::insertIntoBST($root->left, $val);
}
if ($root->val < $val) {
$root->right = self::insertIntoBST($root->right, $val);
}
return $root;
}
public static function insertIntoBST2(?TreeNode $root, int $val): TreeNode
{
$curr = $root;
while ($curr instanceof TreeNode) {
if ($curr->val < $val) {
if (!$curr->right) {
$curr->right = new TreeNode($val);
return $root;
} else {
$curr = $curr->right;
}
}
if ($curr->val > $val) {
if (!$curr->left) {
$curr->left = new TreeNode($val);
return $root;
} else {
$curr = $curr->left;
}
}
}
return new TreeNode($val);
}
}