I wrote the following code to print a binary tree row by row. The idea is to use 2 queues and alternate between them. I'm swapping the 2 queues by using a $tmp variable. I don't think this is efficient since I'm copying arrays. Is there a better way to do this in php that doesn't involve copying? Thanks.
Btree: http://www.phpkode.com/source/s/binary-tree/binary-tree/btree.class.php
// use 2 queues to get nodes level by level
$currentQueue = array();
$otherQueue = array();
if (!empty($Root)) {
array_push($currentQueue, array($Root->getData(), $Root->getLeft(), $Root->getRight()));
}
$level = 0;
while (!empty($currentQueue)) {
echo "Level " . $level . ": ";
// print and pop all values from current queue while pushing children onto the other queue
$row = array();
while ($node = array_shift($currentQueue)) {
$row[] = $node[0];
$left = $node[1];
$right = $node[2];
if (!empty($left)) {
$data = $left->getData();
$l = $left->getLeft();
$r = $left->getRight();
array_push($otherQueue, array($data, $l, $r));
}
if (!empty($right)) {
$data = $right->getData();
$l = $right->getLeft();
$r = $right->getRight();
array_push($otherQueue, array($data, $l, $r));
}
}
echo implode(' ,', $row);
echo "<br>";
// swap stacks
$tmp = $currentQueue;
$currentQueue = $otherQueue;
$otherQueue = $tmp;
$level++;
}