Download presentation
Presentation is loading. Please wait.
1
CSC 212 Recursion By Dr. Waleed Alsalih
2
Definition A recursive function (method) is one that calls itself. A recursive method must have a basis part and a recursive part. Basis part is usually an if statement that checks a stop condition. If the stop condition is satisfied, no more calls are made. The recursive part is a call to the same method with different parameters.
3
Example: Factorial JAVA recursive method: public int factorial(int n) { if(n==0) return 1; return factorial (n-1)*n; } Basis Part Recursive part
4
Example: Max Input: An array of integers and its size. Output: The largest element in the array. JAVA recursive method: public int max(int[] A, int size) { if(size==1) return A[0]; int m=max(A, size-1); if (A[size-1]> m) return A[size-1]; elsereturn m; }
5
Example: Fibonacci Number JAVA recursive method: public int F(int n) { if(n<=1) return n; return F (n-1)+ F (n-2); }
6
Example: Find Parent in a BT private BTNode findparent (BTNode p, BTNode t) { if (t == null) return null; /* empty tree */ if (t.right == null && t.left == null) return null; else if (t.right == p || t.left == p) return t; /* parent is t */ else { BTNode q = findparent(p, t.left); if (q != null) return q; else return findparent(p, t.right); }
7
Example: Number Of Leaves in a BT private int NumberOfLeaves (BTNode t) { if (t == null) return 0; if (t.right == null && t.left == null) return 1; else return NumberOfLeaves(t.left)+ NumberOfLeaves(t.right); }
8
Example: Tower of Hanoi From Wikipedia: “It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: - Only one disk may be moved at a time. - Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. - No disk may be placed on top of a smaller disk.” From Wikipedia
9
Example: Tower of Hanoi JAVA recursive method: public void ToH (int n, char x, char y, char z) { if(n==1) System.out.printf(“Move the top disk from rod %c to rod %c.%n”, x,z); else{ ToH(n-1,x,z,y); ToH(1,x,y,z); ToH(n-1,y,x,z); } How can you do it without recursion?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.