Home > OS >  How to get the depth
How to get the depth

Time:11-30

Now I have a node class defined as follows

class Node
{
    public int Value { get; set; }
    public List<Node> Nodes { get; set; }
}

and a Node instance

Node r = new Node { Value = 1 };
Node n11 = new Node { Value = 2 };
Node n12 = new Node { Value = 3 };
Node n21 = new Node { Value = 4 };
Node n31 = new Node { Value = 5 };
r.Nodes = new List<Node> { n11, n12 };
n11.Nodes = new List<Node> { n21 };
n21.Nodes = new List<Node> { n31 };

How do I get the length (length = 4) of the longest path (r -> n11 -> n21 -> n31)?

CodePudding user response:

Use recursion function

    public void FindDepth()
    {
        Node r = new Node { Value = 1 };
        Node n11 = new Node { Value = 2 };
        Node n12 = new Node { Value = 3 };
        Node n21 = new Node { Value = 4 };
        Node n31 = new Node { Value = 5 };
        r.Nodes = new List<Node> { n11, n12 };
        n11.Nodes = new List<Node> { n21 };
        n21.Nodes = new List<Node> { n31 };

        int depth = FindDepth(r,1);// here you got it. depth = 4
        
    }

    public int FindDepth(Node n, int depth)
    {
        if( n == null || n.Nodes == null )
        {
            return depth;
        }

        int maxDepth = 0;
        for(int i = 0; i < n.Nodes.Count;i  )
        {
            int d = FindDepth(n.Nodes[i], depth   1);
            if(d > maxDepth)
            {
                maxDepth = d;
            }
        }

        return maxDepth;
    }
  •  Tags:  
  • c#
  • Related