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