var seller = new User(1);
for (var i = 0; i < 3; ++i)
seller.Children.Add(new User(1));
foreach (var child in seller.Children)
{
for (var i = 0; i < 3; ++i)
child.Children.Add(new User(1));
foreach (var child2 in child.Children)
{
for (var i = 0; i < 3; ++i)
child2.Children.Add(new User(1));
foreach (var child3 in child2.Children)
for (var i = 0; i < 3; ++i)
child3.Children.Add(new User(1));
}
}
I'm trying to c开发者_开发知识库reate a tree of objects where each level has 3 objects. I know there's a way to make this a recursive function
private static void AddChildren(User user, int maxDepth)
{
if (maxDepth == 0)
return;
for (var i = 0; i < 3; ++i)
{
var child = new User(1);
AddChildren(child, maxDepth - 1);
user.Children.Add(child);
}
}
And the initial call should be
AddChildren(new User(1), 3); //where 3 is max depth of tree.
what do you mean by each level has three objects? (is it each node has three children?) When do you stop?(i.e what is the height of the tree?)
精彩评论