取子树算法
2015-12-22 15:54
453 查看
<?php /** * * 查找一棵树的子树 * @var unknown_type * @author tianquanjun * */ class demo{ public $tree; //初始化一棵树 public function __construct($tree){ $this->tree = $tree; } //遍历树中的每一个节点,看其是否为指点节点的子树节点 public function handle($id){ $data = array(); foreach ($this->tree as $item){ $res = $this->is_son_node($id,$item); //在字树中,保留 if($res){ $data[] = $item; } } return $data; } //判断节点是否是指定id的子树节点 private function is_son_node($id,$node){ //节点本身是根节点,不是任何节点的子节点 if(empty($node['pid'])){ return false; } //节点的父id恰好是指定的节点,是其儿子节点 if($node['pid'] == $id){ return true; }else{ //节点的父节点不是指定节点,向上遍历,看齐祖辈节点是否是指定节点,递归判断 $parent = $this->get_parent_node($node['pid']); return $this->is_son_node($id, $parent); } } //根据id获取父节点完整信息 private function get_parent_node($id){ foreach ($this->tree as $val){ if($val['id'] == $id){ return $val; } } } } //构造一棵树,数组表示.id表示节点本身编号,pid表示父节点的编号 $tree = array( array('id'=>1,'pid'=>'','name'=>'a'),//root array('id'=>2,'pid'=>'1','name'=>'b'), array('id'=>3,'pid'=>'1','name'=>'c'), array('id'=>4,'pid'=>'1','name'=>'d'), array('id'=>5,'pid'=>'2','name'=>'e'), array('id'=>6,'pid'=>'2','name'=>'f'), array('id'=>7,'pid'=>'3','name'=>'g'), array('id'=>8,'pid'=>'4','name'=>'h'), array('id'=>9,'pid'=>'7','name'=>'i'), array('id'=>10,'pid'=>'7','name'=>'j'), array('id'=>11,'pid'=>'8','name'=>'k'), ); $id = 2; $obj = new demo($tree); $result = $obj->handle($id); echo "<pre/>"; print_r($result);
相关文章推荐
- Python os模块常用部分功能总结
- bash编程之变量、变量类型
- 最小重量机器设计
- Asp.net 生成 导出 Excel 下载
- FastDFS集群整体迁移的问题
- 大规模的I/O流中有效识别大数据并增强时间局部性
- 仿ios日期选择器
- swift字符串相关用法速查表
- node js 连接mysql数据库
- IP地址及子网
- numpy 札记
- 本学期课程教学小结
- ruby on rails mysql2 error
- HDOJ 1028 Ignatius and the Princess III(整数划分)
- 2015年大二上-数据结构-树和二叉树-1-(2)二叉树遍历的递归算法
- devise+cancancan+rolify入门
- UIViewController全部API的学习。
- 第四章 Controller接口控制器详解(6)
- windows下hiredis使用
- CLRS第十一章思考题