Jun-24-2020, 01:46 PM
Jun-24-2020, 03:15 PM
I think it's a technique you should know, yes. Certain problems are expressed more naturally in terms of recursion (e.g. searching trees depth-first).
Jun-24-2020, 03:21 PM
Most programmers use recursion so often that it becomes second nature. To program recursive algorithms, simply program as if you already knew how to do something. For example
The problem is that the above algorithm never stops, we need to add a condition to avoid going into an infinite loop. For example we can add at the beginning:
How to find all of a person's living ancestors? * find all that person's mother living ancestors * add all that person's father living ancestors * if the mother or the father is alive, add them * return all these ancestorsThis is a typical recursive algorithm: I suppose that I know how to find the mother's ancestors or the father's ancestors, which I don't actually know how to do, but I'm simply going to call the algorithm recursively.
The problem is that the above algorithm never stops, we need to add a condition to avoid going into an infinite loop. For example we can add at the beginning:
* If the person was born more than 150 years ago, they have no living ancestors, return the empty setSo the program is written without effort!