Dsa 03
Dsa 03
Structures
Introduction to Non-Linear Structures
Non-linear data structures do not store data sequentially. Elements are arranged hierarchically
or in a networked way, allowing complex relationships.
● Trees
● Graphs
● Heaps
● Tries
Trees
A tree is a hierarchical structure with a root element and children forming a parent-child
relationship.
Binary Trees
A binary tree has nodes with at most two children (left and right).
Example:
class Node:
self.value = value
self.left = None
self.right = None
root = Node(10)
root.left = Node(5)
root.right = Node(15)
Graphs
Graphs consist of vertices (nodes) and edges (connections).
Types of Graphs:
Traversal Methods:
graph = defaultdict(list)
graph[0].append(1)
graph[0].append(2)
graph[1].append(3)
Heaps
A heap is a complete binary tree used for priority queue operations.
Types:
Operations:
Example:
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
print(heapq.heappop(heap)) # Output: 1
Tries
A trie is a special tree used for storing strings efficiently, especially for prefix-based operations.
Use Cases:
● Autocomplete
● Spell checking
● Prefix matching
Implementation:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
Conclusion
Non-linear structures are crucial for solving complex problems that require hierarchical or
networked relationships. Next, we will discuss algorithms for sorting and searching.