开发者

Trouble figuring out the recursion for this

开发者 https://www.devze.com 2023-04-02 04:47 出处:网络
var seller = new User(1); for (var i = 0; i < 3; ++i) seller.Children.Add(new User(1)); foreach (var child in seller.Children)
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?)

0

精彩评论

暂无评论...
验证码 换一张
取 消