Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the depth

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading