msfanboy
msfanboy

Reputation: 5291

C# => Walking down recursively a list with lists to get the last element

I have a node1 with a childrenlist. This childrenlist can have multiple nodes each has its childrenlist and so on.

nod1
....Children
.......node2
.........Children
.......node3
.........Children
............node4
............node5

I need to get the node 5 which is on the most bottom and most right position in the hierarchy.

How do I get this node with a recursive method?

Upvotes: 2

Views: 1854

Answers (1)

Ani
Ani

Reputation: 113442

Well, since you asked for a recursive method, you can do something like:

public static Node GetRightMostLeaf(Node node)
{
    // Argument-checking omitted. You should possibly make this 
    // an instance-method on Node anyway.       

    return !node.Children.Any() ? node : GetRightMostLeaf(node.Children.Last()); 
}

A node's right-most leaf is recursively defined as the right-most leaf of its last child. The base-case is a node with no children; in this case, it is the right-most leaf.

An iterative way of doing this would be:

Node rightLeaf = node;

while(rightLeaf.Children.Any())
{
   rightLeaf = rightLeaf.Children.Last();
}

return rightLeaf;

Upvotes: 6

Related Questions