php 二叉树实现 二叉树排序算法 二叉树数据结构
二叉树在图论中是这样定义的:二叉树是一个连通的无环图,并且每一个顶点的度不大于3。有根二叉树还要满足根结点的度不大于2。有了根结点之后,每个顶点定义了唯一的父结点,和最多2个子结点。然而,没有足够的信息来区分左结点和右结点。如果不考虑连通性,允许图中有多个连通分量,这样的结构叫做森林。
class Node
{
public $key = null;
public $left = null;
public $right = null;
public function __construct($key)
{
$this->key = $key;
}
}
class BinaryTree
{
protected $root = null;
protected $nums = [];
protected function __construct($nums)
{
$this->nums = $nums;
}
protected insertNode(&$node, $newNode)
{
if ($node->key > $newNode->key) {
if (is_null($node->left)) {
$node->left = $newNode;
} else {
$this->insertNode($node->left, $newNode);
}
} else {
if (is_null($node->right)) {
$node->right = $newNode;
} else {
$this->insertNode($node->right, $newNode);
}
}
}
/**
* 生成二叉树
*/
public function general()
{
foreach ($this->nums as $num) {
$node = new Node($num);
if (is_null($this->root)) {
$root = $node;
} else {
$this->insertNode($this->root, $node);
}
}
}
/**
* 中序遍历
*/
public function inItera($node)
{
if (!is_null($node->left)) {
$this->inItera($node->left);
}
echo $node->key.' ';
if (!is_null($node->right)) {
$this->inItera($node->right);
}
}
/**
* 前序遍历
* @param $node
*/
public function preItera($node)
{
echo $node->key.' ';
if (!is_null($node->left)) {
$this->preItera($node->left);
}
if (!is_null($node->right)) {
$this->preItera($node->right);
}
}
/**
* 后续遍历
* @param $node
*/
public function afterItera($node)
{
if (!is_null($node->left)) {
$this->afterItera($node->left);
}
if (!is_null($node->right)) {
$this->afterItera($node->right);
}
echo $node->key.' ';
}
}
$nums = [8, 3, 10, 1, 4, 14, 6, 7, 13];
$bin_tree = new BinaryTree($nums);
$bin_tree->general();
$bin_tree->inItera();