当前位置: 首页 > 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.jsqmd.com/news/980913/

相关文章:

  • 2026年6月最新版苏州第三方CMACNAS甲醛检测治理口碑名单:万清CMA检测中心等5家深度测评 - 一休咨询
  • Off-Policy Actor-Critic 与重要性采样
  • Python开发工程师全景解析:岗位职责·各城市薪资·发展前景·高考志愿填报(2026版)
  • 2026如何提升营销岗位的职场能力和核心竞争力
  • 99个免费公共Tracker终极指南:让BT下载速度飙升300%的完整方案
  • Bili23 Downloader 技术解析:B站流媒体架构与API交互机制研究
  • 2024 LLM开发实操指南:本地化部署与RAG微调全链路
  • 黄冈美度天梭+宝玑手表专业回收,26年精选回收店铺排行榜推荐 - 莘州文化
  • LLM代理层消亡史:当模型原生能力让网关退化为透传器
  • 如何在3分钟内为Microsoft Word添加APA第7版参考文献格式?
  • 激活 Change Pointers,让 SAP HR OM 模型只分发变化而不是重发整棵组织树
  • 吉安法穆兰+卡地亚手表专业回收,26年精选回收店铺排行榜推荐 - 莘州文化
  • 计算机毕业设计之django基于python网络安全攻防学习平台
  • 嘉定区配镜深度调研:行业洗牌下,本土品牌如何突围?—— 以嘉艺眼镜公场为例 - 国麟测评
  • 双喜临门|腾视科技杭州总部及深圳子公司乔迁新址,以全新姿态奔赴新征程!
  • 深度解析 Deep-Live-Cam:从原理到实战的 AI 换脸技术指南
  • douyin-downloader:如何通过三层架构设计实现抖音内容的高效批量采集
  • 高校信息安全课用的Python版CA证书系统(带源码+部署指南+全流程截图)
  • 从拍照到识别:一条龙搞定K210物体检测项目(Mx-yolov3 + 自动拍照脚本 + 脱机部署)
  • 终极免费指南:如何用Wand-Enhancer解锁WeMod完整专业功能
  • 别再让雷劈了你的设备!手把手教你为RS485接口选配TVS、GDT和TBU(附IEC标准解读)
  • 5分钟掌握KH Coder:零编程文本挖掘与数据分析的终极指南
  • LLM技术雷达:推理优化、长上下文与评估可信度实战指南
  • 重大升级|大家反映配置最复杂的“会务报名”也变成“点哪儿改哪儿”啦!
  • Ansys仿真许可优化六步法,两家工具自动化程度
  • 83-Java 自动装箱和拆箱
  • Steam成就管理终极教程:如何快速解锁、重置和管理你的Steam成就
  • 莲湖区家政公司选型:防水补漏、通马桶与保姆月嫂护工参考 - 资讯速览
  • Applite:如何让Mac软件管理变得像App Store一样简单?
  • MATLAB实现TDOA+AOA混合定位仿真:含坐标转换、三角解算与误差分析