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;
}
<strong><span style="font-size:18px;color:#3333ff;"> The easiest way to write a recursive method is to strictly follow a pattern:</span></strong>
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?" You need three things to make recursion work:
If you cannot guarantee those three things then do not use a recursive solution.
百家之言: 首先是思想方法上要转变,不要试图解决问题(这是常规的思考方式),而应该“鼠目寸光”地只想解决一点点,要点是,解决一点点之后,剩下来的问题还是原来的问题,但规模要比原问题小了。 当你的问题分析透彻,何时使用递归就会自然明了。递归只是一种函数调用的技巧,不是解决问题的公式。一个问题可以用递归做,也可以不用递归做,递归不是必须的。所以,理解你需要解决的问题,想清楚解决问题的步骤方法,你会突然发现,原来可以用递归来简化问题。不要一开始就想着如何用递归。 其实递归和循环是等价的,你可以用循环解决的问题,都可以用递归来解决。也就是说,你可以尝试着观察自己所写过的使用了循环结构的代码,然后试图对它们进行一个``定义上''的归纳,比如一个数的阶乘的计算方法是n*(n-1)*...*2*1,它的定义可以想成是n*(n-1)!,这样,你就把一个循环变成了一个递归了。只要练习多了,你就会自然而然地用递归的方式来想问题了。关键一点就是: 刷题目,图的广度、深度遍历、动态规划等等,刷个几十道。 个人感觉和建议,有2点:
试着在脑子里跑代码,看着程序,一行一行的看,脑子存着一个一个的中间变量,跟着变。
|