• 取子树算法


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

      

  • 相关阅读:
    阅读笔记——增强学习3
    阅读笔记——增强学习2
    阅读笔记——增强学习1
    阅读笔记十六
    阅读笔记十五
    MVC实例应用模式
    MVC浅谈
    设计模式理解
    某系统质量属性设计实现详述
    《大型网站架构》浅读有感
  • 原文地址:https://www.cnblogs.com/taijun/p/5066931.html
Copyright © 2020-2023  润新知