繁体   English   中英

寻找一种在php中2个队列之间交替的有效方法

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

我编写了以下代码来逐行打印二叉树。 这个想法是使用2个队列并在它们之间交替。 我正在使用$ tmp变量交换2个队列。 我不认为这是有效的,因为我正在复制数组。 有没有更好的方法在不涉及复制的PHP中执行此操作? 谢谢。

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

如果您只想避免阵列复制,您可以:

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

但是,如果您真的想要优化此代码,我建议您从KnuthCormen等人那里找到广度优先搜索算法,并在PHP中实现它(或找到现有的实现)。

还要确保您确实需要优化此代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM