Graphs are intimidating, but the truth is that they're the almost exactly the same as Trees. The only difference is that graphs can contain cycles in them.
Problem: Given a node in a graph node
, return the total number of nodes in the graph.
Example:
1. Recursion
To solve this problem, you should find a recursion involving the number of nodes in the graph numNodes(node). The total number of nodes in a graph is just the 1 node you're standing at, plus all the nodes in all of the neighbors' graphs. Here's the recursion:
2. Base case
The recursion will enter an infinite loop if there are any cycles in the graph.
To prevent infinite loops, you should keep track of all the nodes you've seen so that you never visit a node twice. If you've already seen a node, you should return 0 to stop the recursion and avoid double counting the node. Here's the base case:
It turns out that when you use graphs, you typically don't need to create a base case for null nodes. This is because function calls to numNodes are made by looping over the neighbors
array. If there are no neighbors, numNodes won't be called at all.
3. Code
To code this up, we can combine the recursion and base case. Here's the code:
Time Complexity O(n). We loop through every node in the graph.
Space Complexity O(n). We store all the nodes in a set. We also store the call stack in memory.
To recap, when you deal with graphs you should keep track of the nodes that you've visited to avoid infinite cycles.
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()