I want to count the number of all children in any level of a Tree Structure. The Tree isn't binary, so a node can have more than 2 children. Right now I have created a recursive function that does that job, but it is really slow. I need a faster way, but I can't do it in any other way.
So, let's say we have that table:
NodeID | ParentID
-------------------
1 | 0
2 | 1
3 | 1
4 | 2
5 | 1
6 | 2
7 | 3
8 | 5
9 | 6
10 | 8
11 | 6
11 | 6
• 1
• 2
• 4
• 6
• 9
• 11
• 12
• 3
• 7
• 5
• 8
• 10
So, if I want to get the children number of node 1, the number should be 11 instead of 3. The same thing for Node 2. The number should be 5 instead of 2.
This is the Recursive function I have created in PHP, but it is SLOW:
function count_all_nodes($connection, $element_id, $elements=false, $i=0) {
if (!$elements) {
$result = mysqli($connection, "SELECT `node_id`, `parent_id` FROM `elements`");
while ($row = mysqli_fetch_array($result)) {
$sub_elements["node_id"] = $row["node_id"];
$sub_elements["parent_id"] = $row["parent_id"];
$elements[] = $sub_elements;
}
}
foreach ($elements as $element) {
if ($element["parent_id"] == $element_id) {
$i++;
$i += count_all_nodes($connection, $element_id, $elements);
}
}
return $i;
}
Is there any way I can avoid this recursive function?
Thank you!