层级遍历优化

This commit is contained in:
hk 2019-09-23 21:51:23 +08:00
parent bc975cca37
commit 21ddc39e2b
2 changed files with 16 additions and 15 deletions

View File

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

View File

@ -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." ";