I have a Tree Structure where each node has 5 child nodes and more than that are not allowed. I wish to traverse this tree in breadth-first search manner.
Now I wish to calculate empty node from selected parent using breadth-first search manner.
e.g.
- if given parent is 1, then function must return node 4 because it has positions available.
- If given parent is 2, then it must return node 7
I am using PHP(codeigniter) + Mysql for this.
My controler
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;
}
and my model
//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;
}
}
Database
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;
Where I stuck up!
I am able to traverse till node 6 by above code. but in next iteration i have need to check @ node 7 since nodes will be in order 5 rase to n and it is not finite tree structure.
next tree traversal order 7 8 9 10 11 12 13 14 16 ......