取子树算法

<?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);

  

posted @ 2015-12-22 15:54  tai君  阅读(675)  评论(0编辑  收藏  举报