php无序树实现方法

本文实例讲述了php无序树实现方法。分享给大家供大家参考。具体如下:

运行效果如下图所示:

php代码如下:

<?php
/*
用php写的无序树
 */
 class unorderedTree{
 // 节点id计数器
 protected $nodeId=0;
 // 树的深度
 protected $depth=0;
 // 树的节点数,
 protected $nodesCount=0;
 // 树的度 @todo: 使其发挥作用
 public $degree=" to be implent";
 // 根节点id
 // 由于树有多种从根节点开始操作,不想每次遍历树到顶找root,用一个变量始终指向根节点
 protected $rootid=null;
 // 子节点集合, k-v 为 nodeid=>(stdclass)node
 // 一些树的实现常常是采用节点和树同一class,这里节点是使用 stdclass{ data, parent, id , childrenIds} ,因我认为节点和树应为两种对象,且stdclass要轻于树的class
 // 节点格式说明: $this->nodes[nodeId] = new stdclass{ id ,parentId, childrenIds, data }
 // id: 节点id
 // parentId: 节点父节点id
 // childrenIds: 子节点的id 不想每次遍历树确定层次关系
 // 注意: 节点中, #只保存其自身数据和其子节点id的集合#, 子节点的数据通过从树 $tree->nodes[ $node->childrenIds[a_child_id] ] 访问
 // data: 节点中包含的数据,如节点名称等属性数据
 protected $nodes=array();
 // 用户自定义访问节点
 protected $userVisitFunction=null;
 /* 分组: 类的基本函数 */
 // @todo: 构造树
 public function __construct(){
 }
 // @todo: 销毁树
 public function __destruct(){
  unset($this->nodes) ;
 }
  //------------ 获取数据类函数---------------
  // 获取树的深度,
  public function getTreeDepth(){
  return $this->depth;
  }
  // 获取树的节点数目
  public function getCount(){
  return $this->NodesCount;
  }
  // 获取树的度
  public function getDegree(){
  // @todo: 获取树的度(因为对度暂时没什么需要就不实现了 )
  return $this->degree;
  }
  //获取指定节点
  public function getNode($nodeId){
  if(isset($this->Nodes[$nodeId])){
   return $this->Nodes[$nodeId];
  }
  else{
   return false;
  }
  }
  // 获取最新id
  public function getId(){
  return $this->nodeId;
  }
  //获取指定节点高度
  public function getNodeHeight($nodeId){
  if( array_key_exists($nodeId, $this->nodes) ){
   // 此节点已在树里,高度至少为1,每找到一个父节点+1
   $height=1;
   // 记录此树中已经访问过的节点, 用于防止节点构造时互相parent导致此函数死循环且及时结束查找
   $visitedNodesIds=array();
   // 记录当前操作节点的id
   $cid=$nodeId;
   // 当前节点的父节点必须存在于此树中
   // 不用递归
   while( isset($cid) ) {
    if( !in_array($cid,$visitedNodesIds ) ){
     if( $this->rootid===$cid){ //到顶,返回
      return $height;
     }
     $visitedNodesIds[]=$cid;
     $cid= $this->nodes[ $cid ]->parentId;
     $height++;
    }
    else{
     return false;
    }
   }
   return false;
  }
  else{
   return false;
  }
  }
  //获取根节点
  public function getRoot(){
  return (!is_null($this->rootid) ) && $this->nodes[$this->rootid];
  }
  //获取指定节点和其所有子节点构成的数组
  //这是用于获取子树的一个关键基础操作
  public function getSubNodes($nodeId){
  if(isset($this->nodes[$nodeId])){
   $result=array();
   $toVisitNodeIds=array();
   $toVisitedNodeIds[]=$nodeId;
   $result[]=$this->nodes[$nodeId]->id;
   array_shift($toVisitedNodeIds);
   $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$nodeId]->childrenIds);
   while(!empty($toVisitedNodeIds)){
    $toVisitNodeId=array_shift($toVisitedNodeIds);
    $result[]=$this->nodes[$toVisitNodeId]->id;
    $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$toVisitNodeId]->childrenIds);
   }
   return $result ;
  }
  else{
   return false;
  }
  }
  //@todo: 获取由指定节点和其所有子节点构建的子树
  public function getSubTree($nodeid){
  }
  //---------------- 数据更新 -----------------
  public function setId($nodeId){
   $this->nodeId=$nodeId;
   return $this;
  }
  // 创建不重复的(树中未被使用的) 新id
  public function seekId(){
  $this->nodeId++;
  return $this->nodeId;
  }
 public function setVisitFunction($userFunction){
  $this->userVisitFunction=$userFunction;
  }
  //插入子节点,默认为插在根节点下
  public function insertNode($parent_id=null , $data=null){
  //注意node不是class tree
  $node = new stdclass;
  $node->data = $data;
  //树的节点数增加
  $this->nodeCount++;
  // 分配节点id
  $this->seekId();
  $node->id =$this->getId();
  //插入根节点
  if( (is_null($parent_id)) && is_null($this->rootid)){
   $node->parentId = null;
   $node->childrenIds = array();
   $this->depth=1;
   $this->rootid=$node->id;
   $this->nodes [$node->id]=$node;
   return $this;
  }
  elseif( isset($this->nodes[$parent_id]) || is_null($parent_id) ){
  // 插在此树已有节点下
   if(is_null($parent_id)){
    $parent_id=$this->rootid;
   }
   $node->parentId = $parent_id;
   $node->childrenIds = array();
   //更新树的最大深度
   $depth=$this->getNodeHeight($parent_id);
   $this->depth=max($depth+1, $this->depth);
   $this->nodes[$parent_id]->childrenIds []= $node->id;
   $this->nodes [$node->id]=$node;
   return $this;
  }
  else{
   return $this;
  }
  }
  //insert node 的别名
  public function append($parent_id=null , $data=null){
  return $this->insertNode($parent_id,$data);
  }
  // --------------- 数据访问 -----
  //广度优先遍历节点的别名, 全名太长了
  public function b($nodeId=null){
  return $this->breadthTraversal($nodeId);
  }
  // 广度优先遍历节点
  public function breadthTraversal($nodeId=null){
  if(is_null($this->rootid)){
   die("此树为空树,不可访问");
  }
  else{
   //全部遍历
   if(is_null($nodeId) || ( $this->rootid===$nodeId) ){
    $nodeId=$this->rootid;
   }
   $toVisitNodeIds=array();
   $toVisitedNodeIds[]=$nodeId;
   $this->visit( $this->nodes[$nodeId]);
   array_shift($toVisitedNodeIds);
   $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$nodeId]->childrenIds);
   while(!empty($toVisitedNodeIds)){
    $toVisitNodeId=array_shift($toVisitedNodeIds);
    $this->visit( $this->nodes[$toVisitNodeId]);
    $toVisitedNodeIds=array_merge( $toVisitedNodeIds, $this->nodes[$toVisitNodeId]->childrenIds);
   }
  }
  return $this;
  }
  //深度优先的别名
  public function d($nodeId=null){
  return $this->depthTraversall($nodeId);
  }
  // 深度优先遍历
  // 和广度优先的不同实现只在于array_merge的顺序不同而已 ( php array 忒好用啊忒好用 )
  public function depthTraversall($nodeId=null){
  if(is_null($this->rootid)){
   die("此树为空树,不可访问");
  }
  else{
   //全部遍历
   if(is_null($nodeId)){
    $nodeId=$this->rootid;
   }
   $toVisitNodeIds=array();
   $toVisitedNodeIds[]=$nodeId;
   $this->visit( $this->nodes[$nodeId]);
   array_shift($toVisitedNodeIds);
   $toVisitedNodeIds=array_merge( $this->nodes[$nodeId]->childrenIds, $toVisitedNodeIds );
   while(!empty($toVisitedNodeIds)){
    $toVisitNodeId=array_shift($toVisitedNodeIds);
    $this->visit( $this->nodes[$toVisitNodeId]);
    $toVisitedNodeIds=array_merge( $this->nodes[$toVisitNodeId]->childrenIds, $toVisitedNodeIds );
   }
  }
  return $this;
  }
  //访问单个节点
  public function visit($node){
  if(is_null($this->userVisitFunction )){
   return $node->id;
  }
  else{
   return call_user_func($this->userVisitFunction,$node,$this);
  }
  }
 }
?>

希望本文所述对大家的php程序设计有所帮助。

(0)

相关推荐

  • PHP使用递归生成文章树

    因为自己的一个技术站,以文章为主,文章有些是一个系列的,所以想把这些文章归类,同一类的在一个下面. 数据库好设计,无非用id,fatherid来进行归类,fatherid代表父类是那篇文章的id,id是文章的唯一id,层次不限,可以是两层,可以是三层.fatherid为0的表示顶层文章. php代码,主要是递归 function category_tree($fatherid){ //require_once("mysql_class/config.inc.php"); //requi

  • php遍历树的常用方法汇总

    本文实例讲述了php遍历树的常用方法.分享给大家供大家参考.具体如下: 一.递归的深度优先的算法: <?php define('DS', DIRECTORY_SEPARATOR); function rec_list_files($from = '.') { if(!is_dir($from)) { return array(); } $files = array(); if($dh = opendir($from)) { while(false !== ($file = readdir($dh

  • PHP生成树的方法

    本文实例讲述了PHP生成树的方法.分享给大家供大家参考.具体如下: 这个类不是我写的 只添加了getAll()函数 php生成一个树,可以用于产品分类 不知道遍历写的是否优化,如果你有请分享一下吧 -.-! 运行效果如下图所示: 实现代码如下: <?php class Tree { public $data=array(); public $cateArray=array(); public $res=array(); function Tree() { } function setNode (

  • php简单实现无限分类树形列表的方法

    本文实例讲述了php简单实现无限分类树形列表的方法.分享给大家供大家参考.具体如下: $items = array( 1 => array('id' => 1, 'pid' => 0, 'name' => '江西省'), 2 => array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'), 3 => array('id' => 3, 'pid' => 1, 'name' => '南昌市'), 4 =

  • php通过前序遍历树实现无需递归的无限极分类

    本文实例讲述了php通过前序遍历树实现无需递归的无限极分类.分享给大家供大家参考.具体如下: 大家通常都是使用递归实现无限极分类都知道递归效率很低,下面介绍一种改进的前序遍历树算法,不适用递归实现无限极分类,在大数据量实现树状层级结构的时候效率更高. sql代码如下: CREATE TABLE IF NOT EXISTS `category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(50) NOT NULL, `lft` i

  • php从数据库查询结果生成树形列表的方法

    本文实例讲述了php从数据库查询结果生成树形列表的方法.分享给大家供大家参考.具体分析如下: 本代码可以从数据库读取数据生成一个类似于windows的资源管理器的树形列表 <?php /* Here are the database definitions (for Solid) that i use in this code. * It should not be hard to adapt it to another database. */ /* CREATE TABLE dirent_t

  • PHP超牛逼无限极分类生成树方法

    你还在用浪费时间又浪费内存的递归遍历无限极分类吗,看了该篇文章,我觉得你应该换换了. 这是我在OSChina上看到的一段非常精简的PHP无限极分类生成树方法,巧在引用,整理分享了. 复制代码 代码如下: function generateTree($items){     $tree = array();     foreach($items as $item){         if(isset($items[$item['pid']])){             $items[$item[

  • php无序树实现方法

    本文实例讲述了php无序树实现方法.分享给大家供大家参考.具体如下: 运行效果如下图所示: php代码如下: <?php /* 用php写的无序树 */ class unorderedTree{ // 节点id计数器 protected $nodeId=0; // 树的深度 protected $depth=0; // 树的节点数, protected $nodesCount=0; // 树的度 @todo: 使其发挥作用 public $degree=" to be implent&qu

  • asp.net使用DataGridTree实现下拉树的方法

    本文实例讲述了asp.net使用DataGridTree实现下拉树的方法.分享给大家供大家参考.具体实现方法如下: 下拉树实现原理:输出json到客户端,客户端实现动态加载,中间不会和服务端交互.数据量支持上经测试几千还是很快的.本下拉树控件是用c#+js树实现. 2.c# 计算器 计算字符串数学表达式源码 计算数学表达式原理 采用c#实现 很实用 //a.建立两个栈:第一个位操作数栈,第二个操作符符栈!(将栈定义为string类型) //b.对数字来说是无条件压入数字栈中. //c.而对符号来

  • jstree创建无限分级树的方法【基于ajax动态创建子节点】

    本文实例讲述了jstree创建无限分级树的方法.分享给大家供大家参考,具体如下: 首先来看一下效果 页面加载之初 节点全部展开后 首先数据库的表结构如下 其中Id为主键,PId为关联到自身的外键 两个字段均为GUID形式 层级关系主要靠这两个字段维护 其次需要有一个类型 public class MenuType { public Guid Id { get; set; } public Guid PId { get; set; } public string MenuName { get; s

  • javascript先序遍历DOM树的方法

    DOM树由文档中的所有节点(元素节点.文本节点.注释节点等)所构成的一个树结构,DOM树的解析和构建是浏览器要实现的关键功能.既然DOM树是一个树结构,那么我们就可以使用遍历树结构的相关方法来对DOM树进行遍历,同时DOM2中的"Traversal"模块又提供了两种新的类型,从而可以很方便地实现DOM树的先序遍历. 注:本文中的5种方法都是对DOM的先序遍历方法(深度优先遍历),并且只关注Element类型. 1. 使用DOM1中的基础接口,递归遍历DOM树 DOM1中为基础类型Nod

  • php可应用于面包屑导航的递归寻找家谱树实现方法

    本文实例讲述了php可应用于面包屑导航的递归寻找家谱树实现方法.分享给大家供大家参考.具体实现方法如下: <?php echo "<pre>"; $area = array( array('id'=>1,'area'=>'北京','pid'=>0), array('id'=>2,'area'=>'广西','pid'=>0), array('id'=>3,'area'=>'广东','pid'=>0), array('

  • Python3遍历目录树实现方法

    本文实例讲述了Python3遍历目录树的方法.分享给大家供大家参考.具体实现方法如下: import os, fnmatch # 检查一个目录,后者某个包含子目录的目录树,并根据某种模式迭代所有文件 # patterns如:*.html,若大小写敏感可写*.[Hh][Tt][Mm][Ll] # single_level 为True表示只检查第一层 # yield_folders 表示是否显示子目录,为False只遍历子目录中的文件, # 但不返回字母名 def all_files(root, p

  • PHP实现无限极分类生成分类树的方法

    本文实例讲述了PHP实现无限极分类生成分类树的方法.分享给大家供大家参考,具体如下: 现在的分类数据库设计基本都是:每一个分类有一个id主键字段,一个pid指向父类的id,这样便可实现无限级分类,取出的数据就是如下的格式: $arr = array( array("id" => 1 , "pid" => 0 , 'cat' => '栏目一'), array("id" => 2 , "pid" =>

  • 深入linux下遍历目录树的方法总结分析

    前几天需要实现对整个目录树的遍历,查阅了相关的一些资料.开始找到的原始的方法是使用readdir()与lstat()函数实现递归遍历,后来发现linux对于目录遍历这种最常用的操作已经提供了很完善的接口:ftw()与nftw().下面就这两种方法具体说明一下.1.手动实现递归1.1 stat()函数族stat函数族包括:stat,fstat以及lstat函数,都是向用户返回文件的属性信息(元数据). 复制代码 代码如下: view plaincopy to clipboardprint?#inc

  • C# TreeView无限目录树实现方法

    本文实例讲述了C# TreeView无限目录树实现方法.分享给大家供大家参考,具体如下: #region 绑定客户树 protected void bindTreeView() { TreeView1.Nodes.Clear(); string userid = Session["UserID"].ToString(); string sqlwr = new SY_ADMINUSER().GetUserIDListByLoginUser(userid, "CUSTOMERSE

  • Python实现简单字典树的方法

    本文实例讲述了Python实现简单字典树的方法.分享给大家供大家参考,具体如下: #coding=utf8 """代码实现了最简单的字典树,只支持由小写字母组成的字符串. 在此代码基础上扩展一下,就可以实现比较复杂的字典树,比如带统计数的,或支持更多字符的字典树, 或者是支持删除等操作. """ class TrieNode(object): def __init__(self): # 是否构成一个完成的单词 self.is_word = Fal

随机推荐