php二叉树 排列,php 二叉树实现 二叉树排序算法 二叉树数据结构

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值