我编写了以下代码来逐行打印二叉树。这个想法是使用 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++;
}