Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively finding the lowest level item in C#

Tags:

c#

recursion

What am I missing in GetLowestLevelFoo? Why do I get the answer A instead of D?

    public class Foo
    {
        public string Name { get; set; }
        public Foo ChildFoo { get; set; }
    }

    [TestFixture]
    public class Recursion
    {
        [Test]
        public void Test()
        {
            Foo foo = new Foo
            {
                Name = "A",
                ChildFoo = new Foo
                {
                    Name = "B",
                    ChildFoo = new Foo
                    {
                        Name = "C",
                        ChildFoo = new Foo
                        {
                            Name = "D"
                        }
                    }
                }
            };

            Assert.AreEqual("D", GetLowestLevelFoo(foo).Name);
        }

        public Foo GetLowestLevelFoo(Foo foo)
        {
            if (foo.ChildFoo != null)
            {
                GetLowestLevelFoo(foo.ChildFoo);
            }
            return foo;
        }
    }
like image 945
Iain Holder Avatar asked Dec 29 '25 19:12

Iain Holder


2 Answers

You only want to return foo when you'r at the lowest level. You were returning it no matter what. If you're not at the lowest level you should return the value returned from your recursive call.

public Foo GetLowestLevelFoo(Foo foo)
    {
        if (foo.ChildFoo != null)
        {
            return GetLowestLevelFoo(foo.ChildFoo);
        }
        else
        {
            return foo;
        }
    }
like image 196
Seth Moore Avatar answered Jan 01 '26 08:01

Seth Moore


edited:

public Foo GetLowestLevelFoo(Foo foo)
{
    if (foo.ChildFoo != null)
    {
        return GetLowestLevelFoo(foo.ChildFoo);
    }
    return foo;
}
like image 42
Bryan Rowe Avatar answered Jan 01 '26 09:01

Bryan Rowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!