该文章仅用于一个小知识点的提醒,以免忘记。
对于任何语言函数内执行递归时的执行顺序都是一样的。先执行递归前的所有内容,再执行递归后的所有内容。而对于多递归的分治法执行就相当于树一样。
例:
package sortingAlgorithm;
public class Test {
public static void test(Integer[] arr, int start, int end){
System.out.println("start:"+start+"; "+"end:"+end);
if(start >= end){
System.out.println("结束递归");
return;
}
int mid = (start+end)/2;
System.out.println(mid);
System.out.println("执行第一个test递归前");
test(arr, start, mid); //递归二分数组的第一个
System.out.println("执行第一个test递归后");
test(arr, mid+1, end);
System.out.println("执行the second递归后");
}
public static void test(Integer[] arr){
int length = arr.length;
test(arr, 0, length-1);
}
public static void main(String[] args) {
Integer[] array = {5,3, 6, 4, 2, 1, 7, 8, 10, 4, 2};
test(array);
}
}
>>>main()
start:0; end:10
5
执行第一个test递归前
start:0; end:5
2
执行第一个test递归前
start:0; end:2
1
执行第一个test递归前
start:0; end:1
0
执行第一个test递归前
start:0; end:0
结束递归
执行第一个test递归后
start:1; end:1
结束递归
执行the second递归后
执行第一个test递归后
start:2; end:2
结束递归
执行the second递归后
执行第一个test递归后
start:3; end:5
4
执行第一个test递归前
start:3; end:4
3
执行第一个test递归前
start:3; end:3
结束递归
执行第一个test递归后
start:4; end:4
结束递归
执行the second递归后
执行第一个test递归后
start:5; end:5
结束递归
执行the second递归后
执行the second递归后
执行第一个test递归后
start:6; end:10
8
执行第一个test递归前
start:6; end:8
7
执行第一个test递归前
start:6; end:7
6
执行第一个test递归前
start:6; end:6
结束递归
执行第一个test递归后
start:7; end:7
结束递归
执行the second递归后
执行第一个test递归后
start:8; end:8
结束递归
执行the second递归后
执行第一个test递归后
start:9; end:10
9
执行第一个test递归前
start:9; end:9
结束递归
执行第一个test递归后
start:10; end:10
结束递归
执行the second递归后
执行the second递归后
执行the second递归后
图解分析如下:
![](https://i-blog.csdnimg.cn/blog_migrate/369fac4c937cbdccc92443852cc2a2b1.jpeg)
更加清晰点的树性递归可以用斐波那契测试:
public class Test {
private int fibonacci(int n){
if (n == 0 || n ==1){
System.out.println(n);
return 1;
}
System.out.println(n);
return fibonacci(n-1)+fibonacci(n-2);
}
public static void main(String[] args) {
Test test = new Test();
int ans = test.fibonacci(5);
System.out.println("Ans:"+ans);
}
}
>>>main()
5
4
3
2
1
0
1
2
1
0
3
2
1
0
1
Ans:8
图解如下:
![](https://i-blog.csdnimg.cn/blog_migrate/93f9e448a997a1ca97a18ff8d010fb4f.jpeg)
总结:
可从输出结果得出:递归相当于二叉树的前序遍历,根节点→左树节点→右树节点。