php广度遍历,php – 以广度优先搜索方式进行的常规树遍历(无限)

我有一个树结构,其中每个节点有5个子节点,不允许多个节点.我希望以广度优先的搜索方式遍历这棵树.

现在我希望使用广度优先搜索方式从所选父节点计算空节点.

例如

>如果给定的父项为1,则函数必须返回节点4,因为它具有可用的位置.

>如果给定父级是2,则它必须返回节点7

我正在使用PHP(codeigniter)Mysql.

我的控制器

public function addmember()

{

$current_node = $this->input->post('member');

$empty_location = $this->tree_model->GetEmptyPositions($current_node);

if($empty_location != 0) {

echo "Position available";

}

else {

$next_nodes = $this->tree_model->GetAllChilds($current_node);

$i=0;

for($i=0;$i<5;$i++){

$result = $this->tree_model->GetEmptyPositions($next_nodes[$i]);

if($result != 0 ) {

$current_node = $next_nodes[$i];

goto exe;

}

}

}

exe:

echo $current_node;

}

和我的模特

//get number of empty nodes of current member

public function GetEmptyPositions($id) {

$this->db->select('empty_position');

$this->db->from('member');

$this->db->where('member_id',$id);

$result = $this->db->get();

if ($result->num_rows() > 0)

foreach($result->result() as $empty_pos)

return $empty_pos->empty_position;

}

//get all childs of current node

public function GetAllChilds($id) {

$this->db->select('member_id');

$this->db->from('member');

$this->db->where('tree_parent_id',$id);

$result = $this->db->get();

if ($result->num_rows() > 0) {

$i = 0;

foreach($result->result_array() as $member_id) {

$member_array[$i] = $member_id['member_id'];

$i++;

}

return $member_array;

}

}

数据库

CREATE TABLE IF NOT EXISTS `member` (

`member_id` int(11) NOT NULL AUTO_INCREMENT,

`datetime` datetime DEFAULT NULL,

`parent_id` int(11) DEFAULT NULL,

`tree_parent_id` int(11) DEFAULT NULL,

`empty_position` tinyint(4) DEFAULT '5', // stores how many empty positions remain if zero move to next node

`name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,

PRIMARY KEY (`member_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

我坚持的地方!

我可以通过上面的代码遍历到节点6.但是在下一次迭代中,我需要检查@ node 7,因为节点将按顺序5到n并且它不是有限树结构.

下一个树遍历令7 8 9 10 11 12 13 14 16 ……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值