Recursive Overview
Recursive: Refers to call their own way in the current method is called recursively
Recursive Category:
1. Direct method calls itself recursively called themselves.
2. Indirect recursion can be called by Method B Method A, Method B calls C method, method C method A calls.
Recursive Notes
Recursive conditions must be limited to ensure that recursion can be stopped, otherwise there will be an infinite loop, leading to a stack memory overflow. Although there are limited conditions, but not too much recursion recursion. Otherwise stack memory overflow will occur. Constructor disables recursion
. 1 Package demosummary.recursive;
2
. 3 public class RecursiveDemo1 {
. 4 public static void main (String [] args) {
. 5 // invoke a method
. 6 a (. 1 );
. 7 // call the method b
. 8 b ();
. 9 }
10
. 11 Private static void a ( int I) {
12 is System.out.println (I);
13 is // add a condition to avoid memory overflow occurs
14 IF (I == 10 ) {
15 return ;
16 }
. 17 A (++ I);
18 is }
. 19
20 is // not limitation, memory overflow may occur
21 is Private static void B () {
22 is System.out.println ( "Method B" );
23 is B ();
24 }
25 }
Recursive cumulative sum
1 package demosummary.recursive;
2
3 /**
4 * 计算1~n的和
5 * 分析:
6 * num的累和 = num + (num-1)的累和,所以可以把累和的操作定义成一个方法,递归调用
7 */
8 public class RecursiveSum {
9 public static void main(String[] args) {
10 int sum = getSum(5);
11 System.out.println(sum);
12 }
13
14 private static int getSum(int num) {
15 if (num == 1) {
16 return 1;
17 }
18 return num+getSum(num -1);
19 }
20 }
递归求阶乘(同求和一样解法)
1 package demosummary.recursive;
2
3 public class RecursiveFactorial {
4 public static void main(String[] args) {
5 int sum = getSum(5);
6 System.out.println(sum);
7 }
8
9 private static int getSum(int num) {
10 //当num=1时,停止递归,防止发生内存溢出现象
11 if (num == 1) {
12 return 1;
13 }
14 return num * getSum(num - 1);
15 }
16 }
递归打印多级目录
1 package demosummary.recursive;
2
3 import java.io.File;
4
5 public class RecursivePrintDir {
6 public static void main(String[] args) {
7 //创建File对象
8 File file = new File(".//filter");
9 //调用打印方法
10 printDir(file);
11 }
12
13 private static void printDir(File dir) {
14 //获取目录的集合
15 File[] files = dir.listFiles();
16 //循环打印目录
17 for (File file : files) {
18 if (file.isFile()) {//判断是否为文件
19 System.out.println("文件的路径:" + file.getAbsolutePath());
20 } else {//判断是否为目录
21 System.out.println("目录的路径:" + file.getAbsolutePath());
22 //是目录则继续往下打印
23 printDir(file);
24 }
25 }
26 }
27 }