You are not creating the tree as you've shown in diagram, rather you're doing something like below:
R
/ \
/ \
a1 a2 (children of this are actually b1 and b2)
/ \
/ \
b1 b2
When you add the b1, b2
as children of a2
you're referencing to the same b1 and b2
that have been alreayd added to a1
.
In next iteration when you add c1 and c2
, according to your algorithm you reference c1 and c2
to both b1 and b2
firstly via a1
but your function does not stop here, it goes again to b1 and b2
this time via a2
, but since c1 and c2
have been already added as children of b1 and b2
, the algorithm gets confuse and goes into forever loop.
To solve this problem:
Find the last level of tree but till last level only use recursive path using one child only.
public boolean addChildren(Node root, Node[] children)
{
if (root.children == null)
{
root.children = children;
return true;
}
else
{
for (int i = 0; i < root.children.Length; i++)
{
/* if it returns true then it was last level
else break */
if(!addChildren(root.children[i], children))
{
/* this is non-last level break */
break;
}
}
}
return false;
}