A recursive function is a self calling function that calls itself directly or indirectly in the body of a function. However, you need to set the conditions of the call, if the conditions are met, then call the function itself, if not satisfied with the termination of the function of the call, and then the current process of the main control back to the previous layer of functions to perform, it may be explained to you, or difficult to understand, Directly on the example
function test ($n) {
echo $n. "";
if ($n >0) {
Test ($n-1);
}else{
echo "<–>";
}
echo $n. ""
}
Test (2)
The final output of this example is 2 1 0<–>0 1 2.
I'll explain why the output is like this.
The first step is to execute Test (2), Echo 2, and then because of 2>0, execute test (1), followed by Echo 2 with no time to execute.
In the second step, execute Test (1), Echo 1, and then because of 1>0, execute test (0), and then there's no time to execute echo 1
Step three, execute test (0), Echo 0, execute test (0), Echo 0, at which point the condition of the 0>0 is not satisfied, the test () function is not executed, but the echo "<–>", and the following echo 0
At this point, the function no longer calls itself, and begins to return the master control of the process to the previous layer of functions to perform, which is to start execution of all the test () functions just before the output of the last echo,0 layer is 1 is the output 1 1 of the previous layer is 2 is the output 2 2 No mountain layer, so the output of the content is 2 1 0<–>0 1 2
Example
, we want to traverse a folder inside all the directories, listing all the files inside, PHP itself with a readdir function, but can only read the current directory, according to this function, I wrote another function, to achieve my needs. The principle of the function is very simple, the main thing is to use a recursive call.
function File_list ($path) {
if ($handle = Opendir ($path)) {
while (false!== ($file = Readdir ($handle))) {
if ($file!= "." && $file!= "...") {
if (Is_dir ($path.) /". $file)) {
echo $path. ":". $file. " <br> get rid of all the non-directory files shown in this row
File_list ($path. " /". $file);
} else {
echo $path. ":". $file. " <br> ";
}
}
}
}
}
Example
Application of recursion
Sequential traversal of binary tree
void Inorder (Bintree t) {
if (t) {
Inorder (t->lchild);
printf ("% C ", T->data);
Inorder (t->rchild);
}
}