Search code examples
phparraysperformancereferencecopying

looking for an efficient way to alternate between 2 queues in php


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 source

// 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++;
}

Solution

  • If all you want is to avoid the array copy you can:

    $tmp = & $currentQueue;
    $currentQueue = & $otherQueue;
    $otherQueue = & $tmp;
    

    But if you're really trying to optimize this code I would suggest finding a Breadth-First Search algorithm from Knuth or Cormen et al and implement it in PHP (or find an existing implementation).

    Also be sure you actually need to optimize this code.