php二叉搜索,【PHP 实现数据结构】二叉查找树

什么是二叉树

在了解二叉查找树之前,我们行了解一下树的概念。树由节点和层级关系组成,是一种非线性的数据结构。就像现实中树的叶子和枝干一样。树枝把树叶一片片连接起来,树叶就是节点,树枝就是路径。像这样

3b35516103c45971f896552c700690b1.png

而二叉树是一种特殊的树,它每个节点最多只会有两个节点。像上图,因为节点 D 有三个子节点,它就不能称为二叉树。

什么是二叉查找树

二叉查找树又称为二叉排序数,是一种更特殊的树,首先它是二叉树,最多只会有两个节点,分别称为左节点和右节点,其次它的所有节点中,较小的值保存在左节点,较大的值保存在右节点。像这样

911cb07890c1249cf657d9f1fc43b0bb.png

为了保证值大小的逻辑,在往二叉数里写数据时,就不能像队列或栈一样,直接放在队尾或栈顶了,需要有一定的逻辑处理。

e85fc5089b5c3afb841dd3a52aa9fa27.png

代码实现

我们先实现数据结构和上述的数据逻辑

定义节点

/**

* Class Node

* @property-read $left

* @property-read $right

*/

class Node

{

public $data;

private $left = null;

private $right = null;

public function __construct($data)

{

$this->data = $data;

}

/**

* @param Node $left

*/

public function setLeft(Node $left)

{

$this->left = $left;

}

/**

* @param Node $right

*/

public function setRight(Node $right)

{

$this->right = $right;

}

public function __get($name)

{

if (in_array($name, ['left', 'right'])) {

return $this->{$name};

}

return null;

}

}

二叉查找树

class BinarySortTree

{

/**

* @var Node

*/

public $root;

public function insert($data) {

$node = new Node($data);

if(null == $this->root) {

$this->root = $node;

return;

}

$current = $this->root;

do {

$parent = $current;

if ($node->data < $current->data) {

$current = $parent->left;

if(null == $current) {

$parent->setLeft($node);

}

} else {

$current = $current->right;

if(null == $current) {

$parent->setRight($node);

}

}

} while ($current);

}

}

示例

$bst = new BinarySortTree();

$bst->insert(23);

$bst->insert(45);

$bst->insert(16);

$bst->insert(37);

$bst->insert(3);

$bst->insert(99);

$bst->insert(22);

这样我们就获得了与上述示例图的一致的一个二叉树实例了,执行代码,数据插入流程是这样的

set root 23

current: 23, set right: 45

current: 23, set left: 16

current: 45, set left: 37

current: 16, set left: 3

current: 45, set right: 99

current: 16, set right: 22

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值