如何计算节点数? [英] How to calculate count of nodes?

查看:553
本文介绍了如何计算节点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程如下



I have a class as follows

public class Node 
{
   public List<node> nodes {get ; set;}

}
Public static void main ()
{

   Node n1 = new Node();
   n1.nodes =new List<node>();
   n1.nodes.Add (new Node());
   Node n2 = new Node ();
   n2.nodes = new List<node>();

   n1.nodes.Add(n2);

}







假设这可以像Nodes一样下降到N级在N1中添加可以再次拥有节点,这些节点也可以有节点..



那么如何获得main方法中节点的总数?



我尝试了什么:



我想要有一个返回节点数的函数节点对象。




Suppose this can go to N level down like Nodes added in N1 can have again haves nodes which again can have nodes ..

So How do i get total count of nodes in main method ?

What I have tried:

I want to have function which returns count of nodes of a node object.

推荐答案

有几种方法,但最简单的只是一个简单的递归函数:

There are a couple of ways, but the simplest is just a trivial recursive function:
public int Count { get { return GetCount(this); } }
private int GetCount(Node root)
    {
    int count = 0;
    if (root != null && root.Nodes != null)
        {
        count += root.Nodes.Count;
        foreach (Node node in root.Nodes)
            {
            count += GetCount(node);
            }
        }
    return count;
    }


这篇关于如何计算节点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆