Ryan
Ryan

Reputation: 4414

Trouble figuring out the recursion for this

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 create a tree of objects where each level has 3 objects. I know there's a way to make this a recursive function

Upvotes: 1

Views: 83

Answers (2)

potter
potter

Reputation: 281

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?)

Upvotes: 0

hazzik
hazzik

Reputation: 13364

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.

Upvotes: 5

Related Questions