java 递归算法案例讲解
1、求1-n的和
public static int getSum(int n) {
if(n == 1)
return 1;
return n+getSum(n-1);
}
public static void main(String[] args){
System.out.println(getSum(100));
//5050
}
2、输出斐波那契数列
public static int getFibonacci(int n) {
if(n1)
return 1;
if(n2)
return 1;
return getFibonacci(n-1)+getFibonacci(n-2);
}
public static void main(String[] args){
for(int i = 1;i<=10;i++) {
System.out.print(getFibonacci(i)+" ");
}
//1 1 2 3 5 8 13 21 34 55
}
3、遍历二叉树(让用户输入数据,并排序输出)
class Node {
int value;
Node left;
Node right;
Node(int input){
value = input;
}
}
public class Main {
public static void put(Node node,int number) {
if(number<=node.value) {
if(node.left == null) {
node.left = new Node(number);
}else {
put(node.left,number);
}
}else {
if(node.right == null) {
node.right = new Node(number);
}else {
put(node.right,number);
}
}
}
public static void showasc(Node node) {
if(node.left!=null) {
showasc(node.left);
}
System.out.print(node.value+" &#