Recursion is one of the most powerful and frequently used techniques for solving tree problems.
解决树的问题,递归是最有效也是使用最多的技术。
Typically, we can solve a tree problem recursively using a top-down approach or using a bottom-up approach.
典型地,我们能使用“top-down”从顶到底的方式或者“bottom-up”从底到顶的方式递归解决树的问题。
It is not easy to understand recursion and find out a recursive solution for the problem. It needs practice.
When you meet a tree problem, ask yourself two questions: Can you determine some parameters to help the node know its answer? Can you use these parameters and the value of the node itself to determine what should be the parameters passed to its children? If the answers are both yes, try to solve this problem using a "top-down
" recursive solution.
当你遇到一个树问题时,问你自己两个问题:你能得到一些参数能帮助node知道它自己的结果吗?你能使用这些参数和node的结果去得到什么样的参数被传递给children node吗?如果两个回答都是肯定的,那么试着去解决这个问题,采用“top-down”递归方案。
Or, you can think of the problem in this way: for a node in a tree, if you know the answer of its children, can you calculate the answer of that node? If the answer is yes, solving the problem recursively using a bottom up
approach might be a good idea.
如果你知道children node的结果,就能计算出父node的结果。那么可以采用“bottom-up”的方案。