dp610807 2013-04-01 05:11
浏览 49
已采纳

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

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++;
}
  • 写回答

1条回答 默认 最新

  • douji5329 2013-04-01 05:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号