用PHP构建树

这篇博客介绍了如何在PHP中构建二叉树。通过使用索引来模拟节点的位置,利用递归方法插入节点,并提供了先序遍历的实现,以验证树的正确性。代码示例展示了从根节点开始插入数据并进行先序遍历的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree)。


如图所示即为一颗二叉树。

在C语言中,构建一颗二叉树时,所采用的结构为:

每个节点包含节点的值以及指向左子树和右子树的节点。

但是在PHP中没有结构的概念,所以此处用索引来代替每个节点在树中的位置。

构建时需要用到递归思想。

1.插入根节点。索引值为0,此时树为空,插入该节点值,即node[0] = 根节点的值。
2.插入其他节点。判断当前索引的值是否为空,若空则插入该节点值。若不空则判断当前插入值和当前索引的值的大小。若小,则插入左子树;大,则插入右子树。分别将索引值赋值为2*index+1,2*index+2。

代码如下:
public $node = array(
);

public $index = 0;

public function insert($value){
if(!isset($this->node[$this->index])){
$this->index = strval($this->index);
$this->node[$this->index] = $value;
return;
}
if($value > $this->node[$this->index]){
$this->index = $this->index * 2 + 2;
$this->insert($value);
}else{
$this->index = $this->index * 2 + 1;
$this->insert($value);
}
}

构建完成树之后,采用先序遍历来查看其值是否正确

public function preOrder($index)
{
if (isset($this->node[$index])) {
echo "data_" . $this->node[$index] . " index_" . $index;
echo "<br>";
$this->preOrder($index * 2 + 1);
$this->preOrder($index * 2 + 2);
}
}
先序遍历的思想是采用遍历根节点-左节点-右节点的顺序,即首先遍历根节点是否存在,若存在打印其值,继续遍历其左节点、右节点。

以下为完整代码可以进行测试:
<?php

class Tree
{

public $node = array();

public $index = 0;

public function insert($value)
{
if (!isset($this->node[$this->index])) {
$this->index = strval($this->index);
$this->node[$this->index] = $value;
return;
}
if ($value > $this->node[$this->index]) {
$this->index = $this->index * 2 + 2;
$this->insert($value);
} else {
$this->index = $this->index * 2 + 1;
$this->insert($value);
}
}

public function inn($value)
{
//需要从根节点开始插入,故每次插入节点时将索引置为根节点索引处
$this->index = 0;
$this->insert($value);
}

public function preOrder($index)
{
if (isset($this->node[$index])) {
echo "data_" . $this->node[$index] . " index_" . $index;
echo "<br>";
$this->preOrder($index * 2 + 1);
$this->preOrder($index * 2 + 2);
}
}
}

$tree = new Tree();
$tree->inn(9);
$tree->inn(4);
$tree->inn(5);
$tree->inn(12);
$tree->inn(19);
$tree->inn(16);
$tree->inn(6);
$tree->inn(100);
$tree->preOrder(0);
得到打印结果为:
data_9 index_0
data_4 index_1
data_5 index_4
data_6 index_10
data_12 index_2
data_19 index_6
data_16 index_13
data_100 index_14
构建所得的树如下图所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值