Svick’s solution is fine, but I thought I’d add a bit more general advice. It seems like you are new to writing recursive methods and were struggling a bit there. The easiest way to write a recursive method is to strictly follow a pattern:(书写递归的方法,需要严格按照这个模式。)
Result M(Problem prob)
{
if (<problem can be solved easily>)
return <easy solution>;
// The problem cannot be solved easily.
Problem smaller1 = <reduce problem to smaller problem>
Result result1 = M(smaller1);
Problem smaller2 = <reduce problem to smaller problem>
Result result2 = M(smaller2);
...
Result finalResult = <combine all results of smaller problem to solve large problem>
return finalResult;
}
So suppose you want to solve the problem “what is the maximum depth of my binary tree?”(尝试用该模式写一个方法求二叉树的深度)
int Depth(Tree tree)
{
// Start with the trivial case. Is the tree empty?
if (tree.IsEmpty) return 0;
// The tree is not empty.
// Reduce the problem to two smaller problems and solve them:
int depthLeft = Depth(tree.Left);
int depthRight = Depth(tree.Right);
// Now combine the two solutions to solve the larger problem.
return Math.Max(depthLeft, depthRight) + 1;
}
You need three things to make recursion work:(使用递归必须确保三件事)
The problem has to get smaller every time you recurse. The problem has to eventually get so small that it can be solved without recursion The problem has to be solvable by breaking it down into a series of smaller problems, solving each one, and combining the results. If you cannot guarantee those three things then do not use a recursive solution.