Understand the data structure-stack (basic knowledge)
The following describes several stack-related applications.
Recursion
Call a function directly or indirectly to become a recursive function.
Here is a good example. Let's look at the number of groups below:
Have you found the number rule of this group? Yes, you will find that starting from the third number, each number is the combination of the first two numbers. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + export/camf2ybt6wuujuw.vcd4kpha + PHByZSBjbGFzcz0 = "brush: java;"> public class Test {private static int dieDai (int I) {if (I <2) {return I = 0? 0: 1;} return dieDai (I-1) + dieDai (I-2);} public static void main (String [] args) {for (int I = 0; I <12; I ++) {System. out. println (dieDai (I ));}}}
Note that the first line calls its own method, which is called iteration.
Note:
The biggest fear of writing a recursive program is that the program is stuck in endless recursive calls. Therefore, we must have at least one restriction. When a condition is met, a result will be returned, instead of calling itself.
In fact, the above example code can also be implemented through iteration. You can try to write it. You will find that the code written through iteration looks particularly redundant, what is written by recursion is clear and simple.
Differences between iteration and Recursion:
Iteration uses a loop structure and recursive selection structure.
Recursion can make people think that the program is clearer, concise, and easy to understand. However, a large number of recursive calls will create function copies, which will consume a lot of time and memory, iteration does not require repeated function calls and additional memory usage.
Let's look at the text below to illustrate the relationship between Recursion and stack. A simple conclusion is that the Recursive Execution sequence conforms to the storage structure of the stack.
For the evaluation of the four arithmetic expressions, we can see that the addition and subtraction calculation "9 + (3-1) * 3 + 10/2" = "931-3 * + 10/2 ", what you see behind the mess is the definition of the suffix notation (against the Polish Notation). This is for the computer. You cannot understand it, but the computer can understand it, on the contrary, he cannot understand what we can understand.
I directly attached the suffix notation to the tree, which is very intuitive and clear.