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);
  • 相关阅读:
    ESAPI = Enterprise Security API
    WingIDE中调试GAE(google app engine)
    C# 发送Http请求 WebClient类
    [转]使用Google App Engine Helper for Django
    装上Window7
    最近遇到个关于接口的奇怪的问题
    JNDI概述(转载)
    Google App Engine 中通过自定义Django的filter解决时区问题
    C# string与byte[]互转
    Python天天美味(33) 五分钟理解元类(Metaclasses)[转]
  • 原文地址:https://www.cnblogs.com/wwjchina/p/9626352.html
Copyright © 2011-2022 走看看