Implementing a tree

We will implement a binary tree using a PHP array with a simple recursive function-based traversal. We are just rewriting the functionality using one function instead of a class. Here is the code to do this:

function treeTraverse(array &$tree, int $index = 0,
int $level = 0, &$outputStr = "") : ?bool {

if(isset($tree[$index])) {
$outputStr .= str_repeat("-", $level);
$outputStr .= $tree[$index] . " ";

treeTraverse($tree, 2 * $index + 1, $level+1,$outputStr);
treeTraverse($tree, 2 * ($index + 1), $level+1,$outputStr);

} else {
return false;
}
return null;
}


$nodes = [];
$nodes[] = "Final";
$nodes[] = "Semi Final 1";
$nodes[] = "Semi Final 2";
$nodes[] = "Quarter Final 1";
$nodes[] = "Quarter Final 2";
$nodes[] = "Quarter Final 3";
$nodes[] = "Quarter Final 4";

$treeStr = "";
treeTraverse($nodes,0,0,$treeStr);
echo $treeStr;

If we look at the preceding code, we have simply modified the traversal function and converted it to a standalone function. It is a pure function as we are not modifying the actual input here, which is the $nodes variable. We will construct a string on each level and use that for the output. We can now convert most of our class-based structures to function-based ones.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset