I'm trying to develop an algorithm for an mysql binary tree. It works like that:
Table "network": id_network, parent, child, position
Ir works like that, a new user enters the system with a parent. I search if the parent has childrens already, if doesnt, i add the new user as a child of parent and the position. (If has no childer, go to left first, then right)
Each parent can only have two children, so the next one will have to be his grandson and so on. (From left to right)
I have my php code:
function insertUser($user, $parent) {
$childs = $db -> read('parent =' . $parent); // Return an array with the results from network
$data['parent'] = $parent;
$data['child'] = $user;
if(!$childs[0]) {
$data['position'] = 'left';
$db -> insert($user);
}else{
if(!$childs[1]) {
$data['position'] = 'right';
$db -> insert($user);
}
}
}
I have this block and I know that only with this I could traverse the whole tree, even if had 300 children below parent.
Could anybody help me what could I do now to achieve an insertion in the first empty space from the left to right. I think it's worth it to notice... I ahve serched the whole internet but the approach I want, I cannot find and cannot create too.