• PHP 实现二叉树


    代码

     1 <?php
     2 
     3 /*----------------
     4 + 二叉树
     5 ----------------*/
     6 
     7 class BTree
     8 {
     9     // 数据域
    10     protected $data;
    11     // 左子树
    12     protected $leftNode;
    13     // 右子树
    14     protected $rightNode;
    15 
    16     public function __construct($data = 0)
    17     {
    18         $this->data = $data;
    19     }
    20 
    21     /**
    22      * @param object $leftNode
    23      */
    24     public function setLeftNode(BTree $leftNode = null)
    25     {
    26         $this->leftNode = $leftNode;
    27     }
    28 
    29     /**
    30      * @param object $rightNode
    31      */
    32     public function setRightNode(BTree $rightNode = null)
    33     {
    34         $this->rightNode = $rightNode;
    35     }
    36 
    37     public function getLeftNode()
    38     {
    39         // 判断自己瞎写的,当访问子节点不存在的时候,就重新实例化当前节点,data默认赋值为0,表示空节点。反正能够表示子节点不存在哈哈
    40         if (!isset($this->leftNode)) {
    41             return new self;
    42         }
    43         return $this->leftNode;
    44     }
    45 
    46     public function getRightNode()
    47     {
    48         if (!isset($this->leftNode)) {
    49             return new self;
    50         }
    51         return $this->rightNode;
    52     }
    53 
    54     public function getData()
    55     {
    56         return $this->data;
    57     }
    58 }
    59 
    60 $rootNode = new BTree(1);
    61 $zuo1Node = new BTree(2);
    62 $you1Node = new BTree(3);
    63 $zuo21Node = new BTree(4);
    64 $you21Node = new BTree(5);
    65 $zuo22Node = new BTree(6);
    66 $rootNode->setLeftNode($zuo1Node);
    67 $rootNode->setRightNode($you1Node);
    68 $zuo1Node->setLeftNode($zuo21Node);
    69 $zuo1Node->setRightNode($you21Node);
    70 $you1Node->setLeftNode($zuo22Node);
    71 echo '访问的节点不存在时,返回空,0表示空节点,或者设置为null也行.<br>';
    72 print_r($rootNode->getLeftNode()->getLeftNode()->getRightNode()->getData());
    73 echo "<br>访问存在的节点,可以正常获取数据<br>";
    74 print_r($rootNode->getLeftNode()->getRightNode()->getData());
    PHP 二叉树
  • 相关阅读:
    阿里云主机centos设置虚拟内存
    MySQL表名不区分大小写的设置方法
    java.security.KeyException
    Java.net.URLConnection和Apache HTTPClient的主要区别对比
    linux常用命令
    minerd
    kill常用
    阿里云centos 6安装Nginx+PHP+MySQL
    打开MySQL数据库远程访问的权限
    centos 安装MySql 5.6
  • 原文地址:https://www.cnblogs.com/bneglect/p/12568462.html
Copyright © 2020-2023  润新知