curriculum/challenges/english/blocks/review-graphs-and-trees/67f39e06b8a11b2de9ccd361.md
A graph is a set of nodes (vertices) connected by edges (connections). Each node can connect to multiple other nodes, forming a network. The different types of graphs include:
Graphs are used in various applications such as maps, networks, recommendation systems, dependency resolution.
This involves visiting all the nodes in a graph. The two main algorithms are:
Breadth-First Search (BFS)
Depth-First Search (DFS)
Graphs can be represented in two main ways:
Adjacency List
Adjacency Matrix
A tree is a special type of graph that is acyclic and connected. Key properties include:
The most common types of trees are:
Binary Trees
Binary Search Trees (BST)
Also known as prefix trees, they are used to store sets of strings, where each node represents a character.
Shared prefixes are stored only once, making them efficient for tasks like autocomplete and spell checking.
Search and insertion operations have a time complexity of O(L), where L is the length of the string.
A priority queue is an abstract data type where each element has a priority.
Queues and stacks consider only the order of insertion, while priority queues consider the priority of elements.
Standard queues follow FIFO (First In First Out) and stacks follow LIFO (Last In First Out). However, in a priority queue, elements with higher priority are served before those with lower priority, regardless of their insertion order.
It's a specialized tree-based data structure with a very specific property called the heap property.
The heap property determines the relationship between parent and child nodes. There are two types of heaps:
Max-Heap
Min-Heap
heapq module exampleimport heapq
# Create empty heap
my_heap = []
# Insert elements
heapq.heappush(my_heap, 9)
heapq.heappush(my_heap, 3)
heapq.heappush(my_heap, 5)
print(my_heap) # [3, 9, 5]
# Remove smallest element
print(heapq.heappop(my_heap)) # 3
print(my_heap) # [5, 9]
# Push + Pop in one step
print(heapq.heappushpop(my_heap, 7)) # 5
print(my_heap) # [7, 9]
# Transform list into heap
nums = [5, 7, 3, 1]
heapq.heapify(nums)
my_heap = []
heapq.heappush(my_heap, (3, "A"))
heapq.heappush(my_heap, (2, "B"))
heapq.heappush(my_heap, (1, "C"))
# Removes lowest number = highest priority
print(heapq.heappop(my_heap)) # (1, "C")
Review the Graphs and Trees topics and concepts.