Java函数递归的实现与应用场景
Java函数递归的实现与应用场景
1、递归的基本原理:递归是指在函数的定义中调用函数的自身,这种方式被称为函数的递归调用。在递归中,函数要调用自身,因此必须有一个终止条件,否则就陷入了无限递归的循环中。
2、Java函数递归的实现:Java函数的递归实现需要满足两个条件:(1)必须有一个基准条件;(2)每次递归调用时必须朝基准条件靠近一步,如此,最后递归地调用将会遇到基准条件。
3、Java函数递归的应用场景:
(1)数学领域:
① 阶乘函数:计算n的阶乘通常用n!表示,即n!=n*(n-1)*...*2*1。递归方式实现阶乘函数,如下所示:
public static int factorial(int n) {
if (n < 0)
return -1;
else if (n == 0 || n == 1)
return 1;
else
return n * factorial(n-1);
}
(2)数据结构和算法:
① 实现判断链表是否回文的方法,例如:1->2->3->2->1 返回 true , 1->2->3->2->4 返回 false
public static boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode head2 = slow.next;
slow.next = null;
ListNode head1 = head;
head2 = reverseList(head2);
while (head1 != null && head2 != null) {
if (head1.val != head2.val) {
return false;
}
head1 = head1.next;
head2 = head2.next;
}
return true;
}
public static ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
② Fibonacii 递归算法:
public static int fib(int n) {
if (n <= 0) {
return 0;
} else if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
(3)实现树的相关问题:
① 遍历二叉树:二叉树的遍历方式可以分为前序遍历、中序遍历和后序遍历。递归算法非常适合实现树的遍历。
class TreeNode {
int value;
TreeNode left;
TreeNode right;
}
public void preorder(TreeNode root){
if(root != null) {
System.out.println(root.value);
preorder(root.left);
preorder(root.right);
}
}
public void inorder(TreeNode root){
if(root != null) {
inorder(root.left);
System.out.println(root.value);
inorder(root.right);
}
}
public void postorder(TreeNode root){
if(root != null) {
postorder(root.left);
postorder(root.right);
System.out.println(root.value);
}
}
总结:函数递归具有代码简洁、易于理解、易于维护的优点,同时,也具有空间和时间上的开销等缺点。递归调用能够更加自然地描述问题的本质,对于某些问题,递归也是一种非常有效的解决方案。在软件开发过程中,应选择适当的递归算法来解决问题。
