0% found this document useful (0 votes)
8 views4 pages

Recursion in DSA with Java Examples

The document provides a comprehensive explanation of recursion in Data Structures and Algorithms (DSA) using Java, including its definition, key components, and practical examples such as factorial calculation, Fibonacci series, and depth-first search (DFS) traversal. It highlights the advantages and disadvantages of recursion, emphasizing the importance of a clear base case and progress toward it in recursive calls. Additionally, it offers a tip for performance considerations in DSA tasks.

Uploaded by

Thireka Ammu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Recursion in DSA with Java Examples

The document provides a comprehensive explanation of recursion in Data Structures and Algorithms (DSA) using Java, including its definition, key components, and practical examples such as factorial calculation, Fibonacci series, and depth-first search (DFS) traversal. It highlights the advantages and disadvantages of recursion, emphasizing the importance of a clear base case and progress toward it in recursive calls. Additionally, it offers a tip for performance considerations in DSA tasks.

Uploaded by

Thireka Ammu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2025/12/2 0:14

Here’s a clear and complete explanation of recursion in DSA using Java, along with runnable
examples and edge case handling.

What is Recursion?

Recursion is a programming technique where a method calls itself directly or indirectly to solve a
problem.
In Data Structures and Algorithms (DSA), recursion is widely used in:

Tree traversals (Inorder, Preorder, Postorder)

Graph traversals (DFS)

Divide and Conquer algorithms (Merge Sort, Quick Sort)

Mathematical problems (Factorial, Fibonacci, GCD, etc.)

Key Components of Recursion

Base Case – Condition to stop recursion (prevents infinite calls).

Recursive Case – The part where the function calls itself with a smaller subproblem.

Example 1: Factorial using Recursion

public class RecursionExample {

// Recursive method to calculate factorial


public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Number must be non-
negative");
}
if (n == 0 || n == 1) { // Base case
return 1;
}
return n * factorial(n - 1); // Recursive case
}

public static void main(String[] args) {


try {
int num = 5;
[Link]("Factorial of " + num + " is: " +
factorial(num));

Bing Writer • Generated with AI 1/4


2025/12/2 0:14

} catch (IllegalArgumentException e) {
[Link]("Error: " + [Link]());
}
}
}

Output:

Factorial of 5 is: 120

Example 2: Fibonacci Series using Recursion

public class FibonacciRecursion {

// Recursive method to find nth Fibonacci number


public static long fibonacci(int n) {
if (n < 0) {
throw new IllegalArgumentException("Index must be non-
negative");
}
if (n == 0) return 0; // Base case
if (n == 1) return 1; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}

public static void main(String[] args) {


int terms = 10;
[Link]("Fibonacci Series: ");
for (int i = 0; i < terms; i++) {
[Link](fibonacci(i) + " ");
}
}
}

Output:

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Example 3: DFS Traversal in Graph using Recursion


Bing Writer • Generated with AI 2/4
2025/12/2 0:14

import [Link].*;

public class DFSRecursion {


private Map<Integer, List<Integer>> graph = new HashMap<>();
private Set<Integer> visited = new HashSet<>();

// Add edge to graph


public void addEdge(int src, int dest) {
[Link](src, k -> new ArrayList<>()).add(dest);
[Link](dest, k -> new ArrayList<>()).add(src); // For
undirected graph
}

// Recursive DFS
public void dfs(int node) {
if ([Link](node)) return;
[Link](node);
[Link](node + " ");
for (int neighbor : [Link](node,
[Link]())) {
dfs(neighbor);
}
}

public static void main(String[] args) {


DFSRecursion g = new DFSRecursion();
[Link](0, 1);
[Link](0, 2);
[Link](1, 3);
[Link](2, 4);

[Link]("DFS Traversal: ");


[Link](0);
}
}

Output:

DFS Traversal: 0 1 3 2 4

Bing Writer • Generated with AI 3/4


2025/12/2 0:14

Advantages of Recursion

Simplifies code for problems with repetitive subproblems.

Natural fit for tree and graph algorithms.

Disadvantages

Higher memory usage (stack frames).

Risk of StackOverflowError if base case is missing or recursion depth is too large.

Sometimes slower than iterative solutions.

✅ Tip: In DSA, always ensure:

A clear base case.

Progress toward the base case in each recursive call.

Consider tail recursion or iteration for performance-critical tasks.

If you want, I can also give you a recursion vs iteration performance comparison in Java for DSA
problems.
Do you want me to prepare that?

Bing Writer • Generated with AI 4/4

You might also like