简单树结构的实现

<?php
//节点类
class TreeNode
{
    //节点数据
    public $data = null;
    //子节点对象
    public $children = [];
    //构造方法传入data
    public function __construct(string $data = null)
    {
        $this->data = $data;
    }
    //添加子节点
    public function addChildren(TreeNode $treeNode)
    {
        $this->children[] = $treeNode;
    }
}

//树结构类
class Tree
{
    //根节点
    public $root = null;
    //传入根节点
    public function __construct(TreeNode $treeNode)
    {
        $this->root = $treeNode;
    }
    //遍历树
    public function traverse(TreeNode $treeNode, int $level = 0)
    {
        //传入节点,默认深度0
        if ($treeNode) {
            //输出深度和数据
            echo str_repeat('-', $level) . $treeNode->data . '<br>';
            //递归遍历该节点子节点、深度+1
            foreach ($treeNode->children as $child) {
                $this->traverse($child, $level + 1);
            }
        }
    }
}

$ceo = new TreeNode('ceo');

$tree = new Tree($ceo);

$cfo = new TreeNode('cfo');
$cto = new TreeNode('cto');
$cmo = new TreeNode('cmo');
$coo = new TreeNode('coo');

$ceo->addChildren($cfo);
$ceo->addChildren($cto);
$ceo->addChildren($cmo);
$ceo->addChildren($coo);

$seniorArchitect = new TreeNode("Senior Architect");
$softwareEngineer = new TreeNode("SoftwareEngineer");

$userInterfaceDesigner = new TreeNode("userInterface Designer");
$qualityAssuranceEngineer = new TreeNode("qualityAssurance Engineer");


$cto->addChildren($seniorArchitect);
$seniorArchitect->addChildren($softwareEngineer);

$cto->addChildren($userInterfaceDesigner);
$cto->addChildren($qualityAssuranceEngineer);

$tree->traverse($tree->root);

 

posted @ 2018-09-11 11:05  苦逼成长印记  阅读(509)  评论(0编辑  收藏  举报