-
Binary Trees:

- Definition: A binary tree is a hierarchical data structure composed of nodes, where each node has at most two children, referred to as the left child and the right child.
- Characteristics:
- Each node in a binary tree may have zero, one, or two children.
- Common operations include traversal (visiting all nodes in a specific order), insertion (adding a new node), deletion (removing a node), and searching (finding a node).
- Use Cases: Representing hierarchical data structures (e.g., file systems, organizational charts), binary search trees, Huffman coding.
-
Use Cases:
- Representing hierarchical data structures (e.g., file systems, organizational charts).
- Binary search trees for efficient searching, insertion, and deletion.
- Huffman coding for data compression.
-
Algorithms: Tree traversal algorithms (e.g., inorder, preorder, postorder), Binary search tree operations.
-
Time Complexity:
- Searching, insertion, deletion in a balanced binary search tree: \(O(\log n)\) on average, but \(O(n)\) in worst case for unbalanced trees.
-
Python Code Example:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Example of creating a binary search tree
def insert(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert(root.left, value)
elif value > root.value:
root.right = insert(root.right, value)
return root
def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.value, end=' ')
inorder_traversal(root.right)
# Example Usage
root = None
root = insert(root, 5)
root = insert(root, 3)
root = insert(root, 7)
inorder_traversal(root) # Output: 3 5 7
-
Heap:

- Definition: A heap is a specialized binary tree-based data structure that satisfies the heap property, where each parent node is greater than or equal to (max heap) or less than or equal to (min heap) its children.
- Characteristics:
- Heaps are commonly implemented as arrays, where the children of the ith node are stored at positions 2i+1 and 2i+2.
- Common operations include insertion (adding an element to the heap) and deletion (removing the minimum or maximum element).
- Use Cases: Priority queues, heapsort algorithm, memory allocation.
-
Use Cases:
- Priority queues.
- Implementing heapsort algorithm.
- Memory allocation in programming languages (e.g., C's malloc uses a heap).
-
Algorithms: Heap-based algorithms include Heapsort and Dijkstra's shortest path algorithm.
-
Time Complexity:
- Insertion: \(O(\log n)\).
- Deletion (extracting min/max): \(O(\log n)\).
- Searching for an element: \(O(n)\).
-
Python Code Example:
import heapq
# Example of using heapq module for min-heap
heap = []
heapq.heappush(heap, 5)
heapq.heappush(heap, 3)
heapq.heappush(heap, 7)
print(heapq.heappop(heap)) # Output: 3