zoukankan      html  css  js  c++  java
  • 简单树结构的实现

    <?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);
  • 相关阅读:
    GDOI 2019 退役记
    SHOI2019 游记
    【WC2014】紫荆花之恋
    PKUWC 2019 & NOIWC2019 比赛总结 Formal Version
    WC 2019 颓废记
    VDUVyRLYJC
    Git学习
    DOM学习笔记
    python基础---->AJAX的学习
    python基础---->进程、线程及相关等
  • 原文地址:https://www.cnblogs.com/wwjchina/p/9626352.html
Copyright © 2011-2022 走看看