层级遍历优化
This commit is contained in:
parent
bc975cca37
commit
21ddc39e2b
@ -185,22 +185,23 @@ class Tree
|
|||||||
* 开始遍历数组queue(从index开始,子节点已经入队列的节点元素不再处理),把左右子节点放入queue,index++
|
* 开始遍历数组queue(从index开始,子节点已经入队列的节点元素不再处理),把左右子节点放入queue,index++
|
||||||
* 持续上述过程,当节点没有子节点时,入队列过程结束,queue里节点的顺序即为层级遍历元素节点的顺序
|
* 持续上述过程,当节点没有子节点时,入队列过程结束,queue里节点的顺序即为层级遍历元素节点的顺序
|
||||||
*/
|
*/
|
||||||
public function levelOrder(&$queue,$index=0){
|
public function levelOrder($queue, $index = 0)
|
||||||
$len=count($queue);
|
{
|
||||||
for($i=$index;$i<$len;$i++){
|
for ($i = $index; $i < count($queue); $i++) {
|
||||||
$node=$queue[$i];
|
$node = $queue[$i];
|
||||||
if($node->left){
|
if ($node->left) {
|
||||||
$queue[]=$node->left;
|
$queue[] = $node->left;
|
||||||
}else{
|
} else {
|
||||||
return;
|
return $queue;
|
||||||
}
|
}
|
||||||
if($node->right){
|
if ($node->right) {
|
||||||
$queue[]=$node->right;
|
$queue[] = $node->right;
|
||||||
}else{
|
} else {
|
||||||
return ;
|
return $queue;
|
||||||
}
|
}
|
||||||
$index++;
|
$index++;
|
||||||
}
|
}
|
||||||
$this->levelOrder($queue,$index);
|
return $queue;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -25,8 +25,8 @@ $tree->insert(18);
|
|||||||
$tree->insert(21);
|
$tree->insert(21);
|
||||||
$tree->insert(38);
|
$tree->insert(38);
|
||||||
|
|
||||||
$q=[$tree->head];
|
|
||||||
$tree->levelOrder($q);
|
$q=$tree->levelOrder([$tree->head]);
|
||||||
|
|
||||||
foreach ($q as $n){
|
foreach ($q as $n){
|
||||||
echo $n->data." ";
|
echo $n->data." ";
|
||||||
|
Loading…
Reference in New Issue
Block a user