我有一个树结构,其中每个节点有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 ……