5 Recursion And Advanced Techniques

Data Structures and Algorithms · Unit 5

Recursion and Advanced Techniques

Exam-focused notes for Recursion and Advanced Techniques (Data Structures and Algorithms, BIT201): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Recursion and Advanced Techniques in short

Recursion is a way of solving a problem by letting a function call itself on a smaller version of the same problem. It gives short and clear solutions for many tasks, such as trees, Tower of Hanoi and Fibonacci numbers.

Recursion and Advanced Techniques: notes

Recursion definition and benefits

Recursion is a technique in which a function calls itself, directly or through another function, until a stopping condition is met. A recursive function needs two parts:

  • Base case: the simple case that is solved directly and stops the recursion.
  • Recursive case: the part that calls the same function with a smaller input.

Example. The factorial is $n! = n \times (n-1)!$ with $0! = 1$.

int fact(int n) {
    if (n == 0) return 1;        // base case
    return n * fact(n - 1);      // recursive case
}

Benefits of recursion:

  • The code is short and easy to read for problems that are naturally recursive.
  • It suits trees, graphs and divide and conquer methods such as merge sort and quick sort.
  • A hard problem is split into smaller copies of itself.
  • It removes the need for explicit loops and extra stacks in some programs.

Limitations of recursion

  • More memory: every call adds a frame to the call stack. A deep recursion can cause stack overflow.
  • Slower: function calls have a cost, so a loop is often faster.
  • Repeated work: some recursive functions solve the same smaller problem again and again. Naive Fibonacci is the standard case.
  • Hard to debug: following many nested calls is harder than following a loop.
  • No base case or a wrong one causes infinite recursion.

Many recursive programs can be rewritten with loops. For example, the factorial can use a simple for loop and needs only $O(1)$ extra space.

What this unit covers

  • Recursion definition and benefits
  • Limitations of recursion
  • Stack usage in recursion
  • Tower of Hanoi algorithm and tracing
  • Recursive Fibonacci number calculation
  • Recursive algorithm design

Limitations of recursion

2082 · 5 marks

List the limitation of recursion. How do you delete the node in BST? [2+3]

Show solved answer

Limitations of Recursion and Deletion in BST


Limitations of Recursion [2 marks]

  1. Stack Overflow: Each recursive call uses stack memory. For deep recursion (large input), the call stack may overflow, causing program crash.

  2. High Memory Usage: Every function call requires stack frame allocation (for parameters, local variables, return address), consuming more memory than iterative solutions.

  3. Slower Execution: Function call overhead (pushing/popping stack frames) makes recursion slower compared to equivalent iterative approaches.

  4. Difficult to Trace/Debug: The flow of recursive programs is harder to follow and debug compared to iterative programs.

  5. Redundant Computations: Without memoization, some recursive algorithms (e.g., naive Fibonacci) recompute the same subproblems repeatedly.


Deletion of a Node in BST [3 marks]

When deleting a node from a Binary Search Tree, there are three cases:


Case 1: Node is a Leaf Node (No Children)

  • Simply remove the node by setting the parent's pointer to NULL.
Delete 20:
    30                30
   /        -->      /
  20               (NULL)

Case 2: Node has One Child

  • Replace the node with its only child (bypass the node).
Delete 30:
    30                20
   /        -->
  20

Case 3: Node has Two Children

  • Find the inorder successor (smallest node in the right subtree) OR inorder predecessor (largest node in the left subtree).
  • Copy its value to the node to be deleted.
  • Delete the inorder successor/predecessor (which has at most one child).
Delete 50:
        50                  60
       /  \      -->       /  \
      30   70             30   70
          /
         60

Inorder successor of 50 is 60.
Copy 60 to node 50, then delete original 60.

Algorithm (Pseudocode)

DELETE(root, key):
  if root == NULL:
      return NULL
  if key < root.data:
      root.left = DELETE(root.left, key)
  else if key > root.data:
      root.right = DELETE(root.right, key)
  else:
      // Case 1 & 2: 0 or 1 child
      if root.left == NULL:
          return root.right
      else if root.right == NULL:
          return root.left
      // Case 3: 2 children
      successor = FIND_MIN(root.right)
      root.data = successor.data
      root.right = DELETE(root.right, successor.data)
  return root

Summary Table

CaseConditionAction
1No childrenRemove node directly
2One childReplace node with its child
3Two childrenReplace with inorder successor, then delete successor
Open this answer on its own page →

Tower of Hanoi algorithm and tracing

2080 · 5 marks

Define recursion. Explain Tower of Hanoi (TOH) with example. [5]

Recursion is a programming technique in which a function calls itself directly or indirectly to solve a problem. A recursive function solves a problem by breaking it down into smaller subproblems of the same type until it reaches a base case (terminating condition) that can be solved directly wit...

Open this answer on its own page →

2078 · 5 marks

Define recursion. Explain Tower of Hanoi algorithm in detail. [5]

Recursion is a programming technique in which a function calls itself directly or indirectly to solve a problem. A recursive function solves a problem by breaking it down into smaller subproblems of the same type until it reaches a base case (terminating condition) that can be solved directly wit...

Open this answer on its own page →

0 · 5 marks

Define recursive algorithm. Write recursive TOH algorithm? [5]

A recursive algorithm is an algorithm that calls itself directly or indirectly to solve a problem by breaking it down into smaller subproblems of the same type. It must have: - Base case: A condition where the recursion stops (no further recursive call). - Recursive case: The part where the funct...

Open this answer on its own page →

Stack usage in recursion

2079 · 10 marks

How stack is used in recursion? Explain different stack operations. Explain algorithm to convert an infix expression to postfix using stack.[10]

Show solved answer

Stack in Recursion, Stack Operations, and Infix to Postfix Conversion


1. How Stack is Used in Recursion (2 marks)

When a recursive function is called, the system uses an internal data structure called the call stack (or system stack) to manage function calls.

Mechanism:

  • Every time a function calls itself recursively, the current state (local variables, parameters, and return address) is pushed onto the stack.
  • When the base case is reached, the function returns and the saved state is popped from the stack, resuming execution from where it left off.
  • This continues until the stack is empty and the original call completes.

Example: Factorial of n

factorial(3)
  → calls factorial(2)   [state of factorial(3) pushed]
    → calls factorial(1) [state of factorial(2) pushed]
      → returns 1        [base case]
    ← factorial(2) = 2×1 = 2  [popped]
  ← factorial(3) = 3×2 = 6   [popped]

Stack at deepest point:

Stack (top → bottom)
factorial(1)
factorial(2)
factorial(3)

Stack follows LIFO (Last In First Out) which perfectly models the "last called, first returned" nature of recursion.


2. Stack Operations (3 marks)

A stack is a linear data structure that follows the LIFO principle. The main operations are:

a) PUSH (Insert an element)

Adds an element to the top of the stack.

Algorithm:

PUSH(STACK, TOP, MAXSIZE, ITEM):
1. If TOP = MAXSIZE - 1, then:
      Print "Stack Overflow" and Return
2. Set TOP = TOP + 1
3. Set STACK[TOP] = ITEM
4. Return

b) POP (Delete an element)

Removes and returns the element from the top of the stack.

Algorithm:

POP(STACK, TOP):
1. If TOP = -1, then:
      Print "Stack Underflow" and Return
2. Set ITEM = STACK[TOP]
3. Set TOP = TOP - 1
4. Return ITEM

c) PEEK / TOP

Returns the top element without removing it.

PEEK(STACK, TOP):
1. If TOP = -1, then:
      Print "Stack is Empty" and Return
2. Return STACK[TOP]

d) isEmpty

Checks whether the stack is empty.

isEmpty(STACK, TOP):
1. If TOP = -1, Return TRUE
2. Else Return FALSE

e) isFull

Checks whether the stack is full.

isFull(STACK, TOP, MAXSIZE):
1. If TOP = MAXSIZE - 1, Return TRUE
2. Else Return FALSE

3. Algorithm to Convert Infix to Postfix Using Stack (5 marks)

Key Concepts

TermMeaning
InfixOperator between operands: A + B
PostfixOperator after operands: A B +

Operator Precedence Table

OperatorPrecedence
^ (exponent)3 (highest)
*, /2
+, -1 (lowest)
(0 (when in stack)

Algorithm: Infix to Postfix

InfixToPostfix(expression):

1. Initialize an empty STACK and empty output string POSTFIX.
2. Scan the infix expression from LEFT to RIGHT, one token at a time.
3. For each token:

   a. If token is an OPERAND (letter or digit):
         Append it directly to POSTFIX.

   b. If token is '(' (left parenthesis):
         PUSH it onto STACK.

   c. If token is ')' (right parenthesis):
         While TOP of STACK ≠ '(':
            POP from STACK and append to POSTFIX.
         POP '(' from STACK (discard it).

   d. If token is an OPERATOR (+, -, *, /, ^):
         While STACK is not empty AND
               precedence(TOP of STACK) >= precedence(token):
            POP from STACK and append to POSTFIX.
         PUSH the current token onto STACK.

4. After all tokens are scanned:
      While STACK is not empty:
         POP from STACK and append to POSTFIX.

5. Return POSTFIX.

Worked Example

Convert: A + B * C - D

StepTokenStack (bottom→top)Postfix Output
1A(empty)A
2++A
3B+A B
4*+ *A B
5C+ *A B C
6-pop * → pop +, push -A B C * +
7D-A B C * + D
End-(empty)A B C * + D -

Result: A B C * + D -


Another Example with Parentheses

Convert: (A + B) * C

StepTokenStackPostfix
1((
2A(A
3+( +A
4B( +A B
5)(empty)A B +
6*
Open this answer on its own page →

Recursion definition and benefits

2079 · 5 marks

What are the benefits of using recursion? Write a recursive function to find nth Fibonacci number. [5]

  1. Simplicity and Readability: Recursive solutions are often cleaner and easier to understand than their iterative counterparts, especially for problems that are naturally recursive (e.g., tree traversal, factorial). 2. Reduces Code Length: Complex problems can be solved with fewer lines of code,...
Open this answer on its own page →