当前位置: 首页 > news >正文

PHP树结构实现与遍历算法

PHP树结构实现与遍历算法

树是编程中常用的数据结构。分类、组织架构、评论回复都可以用树来表示。今天说说PHP中树结构的实现。

二叉树是最基本的树结构。

```php
class TreeNode
{
public function __construct(
public mixed $data,
public ?TreeNode $left = null,
public ?TreeNode $right = null
) {}
}

class BinaryTree
{
public ?TreeNode $root = null;

public function insert(int $value): void
{
$this->root = $this->insertRecursive($this->root, $value);
}

private function insertRecursive(?TreeNode $node, int $value): TreeNode
{
if ($node === null) return new TreeNode($value);
if ($value < $node->data) $node->left = $this->insertRecursive($node->left, $value);
else $node->right = $this->insertRecursive($node->right, $value);
return $node;
}

// 前序
public function preorder(?TreeNode $node = null): array
{
if ($node === null) $node = $this->root;
if ($node === null) return [];
return array_merge([$node->data], $this->preorder($node->left), $this->preorder($node->right));
}

// 中序
public function inorder(?TreeNode $node = null): array
{
if ($node === null) $node = $this->root;
if ($node === null) return [];
return array_merge($this->inorder($node->left), [$node->data], $this->inorder($node->right));
}

// 后序
public function postorder(?TreeNode $node = null): array
{
if ($node === null) $node = $this->root;
if ($node === null) return [];
return array_merge($this->postorder($node->left), $this->postorder($node->right), [$node->data]);
}

// 层序
public function levelOrder(): array
{
if ($this->root === null) return [];
$result = [];
$queue = [$this->root];
while (!empty($queue)) {
$node = array_shift($queue);
$result[] = $node->data;
if ($node->left) $queue[] = $node->left;
if ($node->right) $queue[] = $node->right;
}
return $result;
}

public function search(int $value): bool
{
$current = $this->root;
while ($current !== null) {
if ($value === $current->data) return true;
if ($value < $current->data) $current = $current->left;
else $current = $current->right;
}
return false;
}
}

$tree = new BinaryTree();
foreach ([5, 3, 7, 2, 4, 6, 8] as $v) $tree->insert($v);

echo "前序: " . implode(', ', $tree->preorder()) . "\n";
echo "中序: " . implode(', ', $tree->inorder()) . "\n";
echo "后序: " . implode(', ', $tree->postorder()) . "\n";
echo "层序: " . implode(', ', $tree->levelOrder()) . "\n";
echo "查找4: " . ($tree->search(4) ? '找到' : '未找到') . "\n";
?>
>

N叉树每个节点可以有多个子节点。

```php
class NaryTreeNode
{
public function __construct(
public mixed $data,
public array $children = []
) {}

public function addChild(NaryTreeNode $child): void
{
$this->children[] = $child;
}
}

class Tree
{
public ?NaryTreeNode $root = null;

public function dfs(?NaryTreeNode $node = null, int $depth = 0): array
{
if ($node === null) $node = $this->root;
if ($node === null) return [];
$result = [['data' => $node->data, 'depth' => $depth]];
foreach ($node->children as $child) {
$result = array_merge($result, $this->dfs($child, $depth + 1));
}
return $result;
}
}
?>

分类树的扁平化和还原。

```php
class CategoryTree
{
public static function fromFlat(array $items, int $parentId = 0): array
{
$tree = [];
foreach ($items as $item) {
if ($item['parent_id'] === $parentId) {
$children = self::fromFlat($items, $item['id']);
$node = ['id' => $item['id'], 'name' => $item['name']];
if (!empty($children)) $node['children'] = $children;
$tree[] = $node;
}
}
return $tree;
}

public static function toFlat(array $tree, int $parentId = 0): array
{
$items = [];
foreach ($tree as $node) {
$items[] = ['id' => $node['id'], 'name' => $node['name'], 'parent_id' => $parentId];
if (!empty($node['children'])) {
$items = array_merge($items, self::toFlat($node['children'], $node['id']));
}
}
return $items;
}
}
?>

树结构在PHP中很常用。文件系统、组织架构、评论回复、菜单导航都可以用树来表示。理解树的遍历和操作在处理层次结构数据时很有帮助。递归是处理树的核心方法。

http://www.rkmt.cn/news/1492647.html

相关文章:

  • Python开发工程师全景解析:岗位职责·各城市薪资·发展前景·高考志愿填报(2026版)
  • Off-Policy Actor-Critic 与重要性采样
  • 99个免费公共Tracker终极指南:让BT下载速度飙升300%的完整方案
  • 2024 LLM开发实操指南:本地化部署与RAG微调全链路
  • LLM代理层消亡史:当模型原生能力让网关退化为透传器
  • 吉安法穆兰+卡地亚手表专业回收,26年精选回收店铺排行榜推荐 - 莘州文化
  • 嘉定区配镜深度调研:行业洗牌下,本土品牌如何突围?—— 以嘉艺眼镜公场为例 - 国麟测评
  • LLM技术雷达:推理优化、长上下文与评估可信度实战指南
  • douyin-downloader:如何通过三层架构设计实现抖音内容的高效批量采集
  • 高校信息安全课用的Python版CA证书系统(带源码+部署指南+全流程截图)
  • 深度解析 Deep-Live-Cam:从原理到实战的 AI 换脸技术指南
  • 如何快速掌握Calibre豆瓣元数据插件:面向电子书爱好者的完整解决方案
  • MATLAB实现TDOA+AOA混合定位仿真:含坐标转换、三角解算与误差分析
  • Steam成就管理终极教程:如何快速解锁、重置和管理你的Steam成就
  • 51单片机智能插座全套开发资料:DS18B20测温+DS1302定时+LCD1602显示+Proteus仿真+AD原理图+Keil源码
  • 2026济南黄金回收门店实测:六家机构专业设备与鉴定流程横向对比 - 薛定谔的梨花猫
  • FastbootEnhance:告别命令行,用图形化界面解锁Android设备管理新体验
  • Matlab小波神经网络实战包:Morlet小波构建+训练测试全流程代码+双数据集
  • Claude Opus 4.8 的 Token 消耗优化指南:少用 15% 步骤的秘诀(Effort Control + Prompt 精简)
  • STM32F103超频实战:用CubeMX和Keil把ADC采样率推到2.5M以上(附VOFA+波形验证)
  • KeymouseGo:3个步骤掌握鼠标键盘自动化,轻松告别重复劳动
  • 15分钟掌握抖音无水印批量下载:内容创作者的效率革命指南
  • 英国14.7亿美元计划摆脱AI硬件依赖,超级计算机与本土芯片发展能否成功?
  • 医药自动化立体仓库怎么建?从GMP/GSP合规到全程追溯,这3个案例值得借鉴 - 新闻快传
  • 学术检测双线承压?paperxie 分层改写体系,精准化解重复率与 AI 疑似难题
  • 吉林法穆兰+卡地亚手表专业回收,26年精选回收店铺排行榜推荐 - 莘州文化
  • Java 反射机制详解:从原理到实战
  • 推荐一下全国优质的精拔无缝钢管制造厂家 - 品牌推广大师
  • Java五子棋实战项目:Swing图形界面+AI对战+逐行中文注释,新手解压即运行
  • 2026深圳黄金回收哪家强?5 家主流渠道实地测评,解锁变现技巧 - 奢侈品回收测评