Trees and graphs are fundamental data structures in computer science. Here’s a simple explanation, along with Python code examples for both:
Tree:
A tree is a hierarchical data structure that consists of nodes connected by edges. It starts with a root node and branches into child nodes, forming a structure similar to a family tree or organizational hierarchy.
Example:
Let’s create a simple binary tree in Python:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Creating a binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
In this example, we have a binary tree with nodes containing values 1 to 5. Node 1 is the root, and nodes 2 and 3 are its children. Nodes 4 and 5 are children of node 2.
Let’s look at a real-time example of a tree implementation.
Tree: File System Hierarchy
Imagine representing a file system hierarchy as a tree structure. Each folder (directory) is a node, and files are the leaves of the tree. This is a common real-world use case for trees.