Recursively finding the lowest level item in C#
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);
}
开发者_C百科
public Foo GetLowestLevelFoo(Foo foo)
{
if (foo.ChildFoo != null)
{
GetLowestLevelFoo(foo.ChildFoo);
}
return foo;
}
}
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;
}
}
edited:
public Foo GetLowestLevelFoo(Foo foo)
{
if (foo.ChildFoo != null)
{
return GetLowestLevelFoo(foo.ChildFoo);
}
return foo;
}
you need to assign foo with the result of your call to GetLowestLevelFoo.
foo = GetLowestLevelFoo(foo.ChildFoo)
otherwise you are returning what you started with.
As other have now commented, your code recurses back through the stack, returning each "level of "foo" : finally returning the topmost "node."
Try this :
public Foo GetLowestLevelFoo(Foo foo)
{
if (foo.ChildFoo == null) return foo;
return GetLowestLevelFoo(foo.ChildFoo);
}
精彩评论