-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathday 23.php
65 lines (54 loc) · 1.27 KB
/
day 23.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
class Node
{
public $left, $right;
public $data;
function __construct($data)
{
$this->left = $this->right = null;
$this->data = $data;
}
}
class Solution
{
public function insert($root, $data)
{
if ($root == null) {
return new Node($data);
} else {
if ($data <= $root->data) {
$cur = $this->insert($root->left, $data);
$root->left = $cur;
} else {
$cur = $this->insert($root->right, $data);
$root->right = $cur;
}
return $root;
}
}
public function levelOrder($root)
{
$data = [];
$queue[] = $root;
while (!empty($queue)) {
$curr = array_shift($queue);
$data[] = (int)$curr->data;
if ($curr->left !== null) {
$queue[] = $curr->left;
}
if ($curr->right !== null) {
$queue[] = $curr->right;
}
}
echo implode(' ', $data);
}
}
//End of Solution
$myTree = new Solution();
$root = null;
$T = intval(fgets(STDIN));
while ($T-- > 0) {
$data = intval(fgets(STDIN));
$root = $myTree->insert($root, $data);
}
$myTree->levelOrder($root);