有没有一种方法可以将计数变成递归的循环?

发布于 2025-01-23 00:17:59 字数 2091 浏览 0 评论 0原文

我一直在做这项任务,无法围绕如何将自己的循环转换为递归并找到树的深度。是否有可能覆盖所有树木的叶子,而无需循环?因为一棵树可以有很多分支,所以我不确定如何在没有循环的情况下测量深度。

static int RecursiveMethodMeasureDepth(Branch branch)
        {
            int value = 1;
            int highestValue = 1;
            for (int i = 0; i < branch.Count(); i++)
            {
                value = RecursiveMethodMeasureDepth(branch.GetBranch(i)) + 1;
                highestValue = value > highestValue ? value : highestValue;
            }
            return highestValue;
        }

如果有人想知道分支机构,那就是:

public class Branch
    {
        private List<Branch> branches;
        public Branch()
        {
            branches = new List<Branch>();
        }
        public void AddBranch(Branch branch)
        {
            branches.Add(branch);
        }
        public Branch GetBranch(int index)
        {
            return branches[index];
        }
        public int Count()
        {
            return branches.Count;
        }
    }

我添加了一棵树的图片,以及一种创建相同数据结构树的方法:

static Branch initializeTree()
        {
            Branch root = new Branch();
            Branch branch2 = new Branch();
            Branch branch3 = new Branch();
            root.AddBranch(branch2);
            root.AddBranch(branch3);
            Branch branch4 = new Branch();
            branch2.AddBranch(branch4);
            Branch branch5 = new Branch();
            Branch branch6 = new Branch();
            Branch branch7 = new Branch();
            branch3.AddBranch(branch5);
            branch3.AddBranch(branch6);
            branch3.AddBranch(branch7);
            Branch branch8 = new Branch();
            branch5.AddBranch(branch8);
            Branch branch9 = new Branch();
            Branch branch10 = new Branch();
            branch6.AddBranch(branch9);
            branch6.AddBranch(branch10);
            Branch branch11 = new Branch();
            branch9.AddBranch(branch11);
            return root;
        }

[树的示例] [1] [1]:https://i.sstatic.net/bqyu2.png

I've been doing this task and can't wrap my head around how to convert my for cycle to be recursive one AND find the depth of my tree. Is it even possible to cover all the tree's leaves without a for loop? Because a tree can have many branches and I am not sure how to measure the depth without the loop.

static int RecursiveMethodMeasureDepth(Branch branch)
        {
            int value = 1;
            int highestValue = 1;
            for (int i = 0; i < branch.Count(); i++)
            {
                value = RecursiveMethodMeasureDepth(branch.GetBranch(i)) + 1;
                highestValue = value > highestValue ? value : highestValue;
            }
            return highestValue;
        }

if anyone is wondering about the Branch class, there it is:

public class Branch
    {
        private List<Branch> branches;
        public Branch()
        {
            branches = new List<Branch>();
        }
        public void AddBranch(Branch branch)
        {
            branches.Add(branch);
        }
        public Branch GetBranch(int index)
        {
            return branches[index];
        }
        public int Count()
        {
            return branches.Count;
        }
    }

I added a picture of a tree bellow and a method that creates same data structure tree:

static Branch initializeTree()
        {
            Branch root = new Branch();
            Branch branch2 = new Branch();
            Branch branch3 = new Branch();
            root.AddBranch(branch2);
            root.AddBranch(branch3);
            Branch branch4 = new Branch();
            branch2.AddBranch(branch4);
            Branch branch5 = new Branch();
            Branch branch6 = new Branch();
            Branch branch7 = new Branch();
            branch3.AddBranch(branch5);
            branch3.AddBranch(branch6);
            branch3.AddBranch(branch7);
            Branch branch8 = new Branch();
            branch5.AddBranch(branch8);
            Branch branch9 = new Branch();
            Branch branch10 = new Branch();
            branch6.AddBranch(branch9);
            branch6.AddBranch(branch10);
            Branch branch11 = new Branch();
            branch9.AddBranch(branch11);
            return root;
        }

[example of a tree][1]
[1]: https://i.sstatic.net/BqYU2.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幻想少年梦 2025-01-30 00:17:59

如果您想避免在那里循环,但请继续递归调用,则可以使用Linq聚合:

    static int RecursiveMethodMeasureDepth(Branch branch)
    {
        return branch
            .branches
            .Aggregate(1, (depth, b) =>
            {
                var currentDepth = RecursiveMethodMeasureDepth(b) + 1;
                return depth < currentDepth ? currentDepth : depth;
            });
    }

参考
https:https://学习。 microsoft.com/en-us/dotnet/api/system.linq.enumloth.aggregate?view=net-6.0

If you want to avoid having for loop there but keep recursive call you can use LINQ Aggregate:

    static int RecursiveMethodMeasureDepth(Branch branch)
    {
        return branch
            .branches
            .Aggregate(1, (depth, b) =>
            {
                var currentDepth = RecursiveMethodMeasureDepth(b) + 1;
                return depth < currentDepth ? currentDepth : depth;
            });
    }

Reference
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-6.0

泪痕残 2025-01-30 00:17:59

该建议不使用更多的递归,但是它使您可以通过从System.linq名称空间使用.max()来计算深度,而无需使用占位符,并将当前深度作为参数发送到递归方法。

//using System.Linq;

static int RecursiveMethodMeasureDepth(Branch branch, int currentDepth = 1)
{
    if (branch.Count() == 0)
    {
        return currentDepth;
    }
    
    return Enumerable.Range(0, branch.Count())
        .Max(i => RecursiveMethodMeasureDepth(branch.GetBranch(i), currentDepth + 1));
}

用法:

Branch tree;

//initialize tree

int depth = RecursiveMethodMeasureDepth(tree);

null /esporate/71948839/is-is-a-away-away-to-to-to-loop-with-with-count-into-into-recursive-One#ansy-71949107“>此答案方法可以/应该作为分支类中的方法实现。

这样的实现可能看起来像:

//using System.Linq;

public class Branch
{
    //Other properties and methods

    public int Depth => GetDepth();
    
    private int GetDepth(int currentDepth = 1)
    {
        if (!branches.Any())
        {
            return currentDepth;
        }
        
        return branches.Max(branch => branch.GetDepth(currentDepth + 1));
    }
}

并称为如下:

Branch tree;

//initialize tree

int depth = tree.Depth;

示例小提琴在这里

This suggestion does not use more recursion, but it lets you calculate the depth without using placeholders by utilizing .Max() from the System.Linq namespace and sending the current depth as a parameter to the recursive method.

//using System.Linq;

static int RecursiveMethodMeasureDepth(Branch branch, int currentDepth = 1)
{
    if (branch.Count() == 0)
    {
        return currentDepth;
    }
    
    return Enumerable.Range(0, branch.Count())
        .Max(i => RecursiveMethodMeasureDepth(branch.GetBranch(i), currentDepth + 1));
}

Usage:

Branch tree;

//initialize tree

int depth = RecursiveMethodMeasureDepth(tree);

As suggested by dr.null in a comment to this answer, such a class-specific method could/should be implemented as a method in the Branch class.

Such an implementation could e.g. look like:

//using System.Linq;

public class Branch
{
    //Other properties and methods

    public int Depth => GetDepth();
    
    private int GetDepth(int currentDepth = 1)
    {
        if (!branches.Any())
        {
            return currentDepth;
        }
        
        return branches.Max(branch => branch.GetDepth(currentDepth + 1));
    }
}

and be called as follows:

Branch tree;

//initialize tree

int depth = tree.Depth;

Example fiddle here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文