-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeHelper.php
41 lines (34 loc) · 987 Bytes
/
TreeHelper.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
<?php
require_once "TreeNode.php";
function arrayToTree($array) {
// Validate input
if (empty($array)) {
return null;
}
$root = new TreeNode($array[0]);
$queue = new SplQueue();
$queue->enqueue($root);
$i = 1;
while (!$queue->isEmpty()) {
$node = $queue->dequeue();
// Check if we have more elements to process
if ($i < count($array)) {
// Process the node's left child.
if ($array[$i] !== null) {
$node->left = new TreeNode($array[$i]);
$queue->enqueue($node->left);
}
$i++;
}
// Check again if we have more elements to process
if ($i < count($array)) {
// Process the node's right child.
if ($array[$i] !== null) {
$node->right = new TreeNode($array[$i]);
$queue->enqueue($node->right);
}
$i++;
}
}
return $root;
}