二叉树增加中序后续,层级遍历

This commit is contained in:
hkui 2019-09-23 19:15:48 +08:00
parent a8ab74397d
commit 733d00f5b4
3 changed files with 97 additions and 1 deletions

View File

@ -149,4 +149,58 @@ class Tree
$this->preOrder($node->left); $this->preOrder($node->left);
$this->preOrder($node->right); $this->preOrder($node->right);
} }
/**中序遍历
* @param $node
*
*/
public function inOrder($node){
if(empty($node)){
return;
}
$this->inOrder($node->left);
echo $node->data . ' ';
$this->inOrder($node->right);
}
/**
* @param $node
* 后续遍历
*/
public function postOrder($node){
if(empty($node)){
return;
}
$this->postOrder($node->left);
$this->postOrder($node->right);
echo $node->data . ' ';
}
/**
* @param $queue
* @param int $index 从队列(数组)的那个位置开始处理
* 层级遍历
* 首先把节点放入数组记录放入数组的根节点个数index把节点的左右子放入数组
* 开始遍历数组queue(从index开始,子节点已经入队列的节点元素不再处理)把左右子节点放入queue,index++
* 持续上述过程当节点没有子节点时入队列过程结束queue里节点的顺序即为层级遍历元素节点的顺序
*/
public function levelOrder(&$queue,$index=0){
$len=count($queue);
for($i=$index;$i<$len;$i++){
$node=$queue[$i];
if($node->left){
$queue[]=$node->left;
}else{
return;
}
if($node->right){
$queue[]=$node->right;
}else{
return ;
}
$index++;
}
$this->levelOrder($queue,$index);
}
} }

View File

@ -0,0 +1,34 @@
<?php
/**
* Created by PhpStorm.
* User: 764432054@qq.com
* Date: 2019/9/22
* Time: 23:30
*
*二叉树的层级遍历
*/
namespace Algo_24;
require_once '../vendor/autoload.php';
$tree=new Tree(20);
$tree->insert(16);
$tree->insert(30);
$tree->insert(12);
$tree->insert(19);
$tree->insert(10);
$tree->insert(15);
$tree->insert(18);
$tree->insert(21);
$tree->insert(38);
$q=[$tree->head];
$tree->levelOrder($q);
foreach ($q as $n){
echo $n->data." ";
}
echo PHP_EOL;

View File

@ -9,6 +9,7 @@ $tree = new Tree();
$tree->insert(20); $tree->insert(20);
$tree->insert(30); $tree->insert(30);
$tree->insert(40);
$tree->insert(10); $tree->insert(10);
$tree->insert(21); $tree->insert(21);
$tree->insert(22); $tree->insert(22);
@ -16,7 +17,14 @@ $tree->insert(22);
$tree->preOrder($tree->head); $tree->preOrder($tree->head);
echo PHP_EOL; echo PHP_EOL;
var_dump($tree->find(30)); $tree->inOrder($tree->head);
echo PHP_EOL;
$tree->postOrder($tree->head);
echo PHP_EOL;
print_r($tree->find(30));
echo PHP_EOL; echo PHP_EOL;