Data Structures Notes (Recursion, Queues, Trees)
Unit 1: Recursion
1.1 Simulating Recursion Using Stack
- Recursion involves a function calling itself with a modified parameter.
- The system stack is used to store function calls during recursion.
- Each function call is pushed onto the stack, and upon completion, popped from it.
- Example: Factorial computation using recursion.
1.2 Recursion Algorithms
1.2.1 Fibonacci Series:
- A series where each term is the sum of the two preceding terms.
- Formula: F(n) = F(n-1) + F(n-2), with F(0) = 0, F(1) = 1.
- Recursive Implementation Example:
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
1.2.2 Tower of Hanoi:
- Problem: Move all disks from Source (A) to Target (C) using Auxiliary (B), maintaining the order of
disks.
- Rules:
1. Only one disk can be moved at a time.
2. No larger disk can be placed on a smaller one.
- Recursive Formula: T(n) = 2^n - 1
Unit 2: Queues
2.1 Introduction
- Queue is a linear data structure that follows the FIFO (First In First Out) principle.
2.2 Representation: Static & Dynamic
- Static: Fixed size using arrays.
- Dynamic: Variable size using linked lists.
2.3 Queue Operations
- Create: Initialize an empty queue.
- Insert (Enqueue): Add element to the rear.
- Remove (Dequeue): Remove element from the front.
- Display: Show elements in the queue.
2.4 Circular Queue & Priority Queue
- Circular Queue: Front and rear pointers wrap around when the queue is full.
- Priority Queue: Elements are dequeued based on priority instead of position.
2.5 Doubly-Ended Queue (Deque)
- Allows insertion and deletion at both ends (front and rear).
Unit 3: Trees
3.1 Concept & Terminologies
- Node: A data element in a tree.
- Root: Topmost node.
- Leaf: Node with no children.
- Height: Length of the longest path from the root to a leaf.
3.2 Binary Tree & Binary Search Tree (BST)
- Binary Tree: Each node has at most two children.
- BST: A binary tree where left child < parent < right child.
3.3 Representation: Static & Dynamic
- Static: Arrays (seldom used).
- Dynamic: Linked nodes.
3.4 Operations on BST & Heap Tree
- Create: Insert nodes according to BST rules.
- Insert: Place new node in the correct position.
- Delete: Remove a node while preserving tree structure.
- Traversals:
- Preorder: Root -> Left -> Right
- Inorder: Left -> Root -> Right
- Postorder: Left -> Right -> Root
- Non-Recursive Inorder Traversal: Using a stack.
- Counting Nodes: Counting leaf, non-leaf, and total nodes.