I am having some difficulties to delete empty parent node if empty from a trie. I can correctly identify the node that has the value 3, but then I cannot unset nodes that do not have any children.
What am I missing? Do I have to move to receursive function?
This is my code:
function removeWord($word){
global $tree;
$ch=false;
while(strlen($word)>0){
$p="";
$parent=&$tree;
$i=0;
foreach(str_split($word) as $char){
$i++;
$p.=$char;
$parent=&$parent[$char];
if(!$ch && $parent[0]==3 && $p==$word){
unset($parent[0]);
$ch=true;
}
if($ch && $p==$word){
if(empty($parent)){
unset($parent);
}
else{
$word="";
break;
}
$word=substr($word, 0, -1);
}
}
}
}
as example data:
$tree=array("a"=>array("a"=>array()));
$word='aa';
Source:
Array
(
[a] => Array
(
[a] => Array
(
[0] => 3
)
)
)
Wrong output:
Array
(
[a] => Array
(
[a] => Array
(
)
)
)
Expected output: Array ( )
Basically I was overwriting the intial value restoring it to the original ocntent, this is the fixed code using recursive function
function removeWord(&$parent,$word){
if(strlen($word)==0){
if($parent[0]==3){
unset($parent[0]);
}
if(empty($parent)){
unset($parent);
return true;
}
return false;
}
else{
$char=substr($word, 0, 1);
$word=substr($word, 1);
if(removeWord($parent[$char],$word)){
if(empty($parent[$char])){
unset($parent[$char]);
return true;
}
}
return false;
}
}