A Tree is a widely used non-linear data structure that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent-child relationship. Unlike arrays or linked lists, which are linear, trees can have multiple branches.
A tree is a collection of entities called nodes. Nodes are connected by edges. Each node contains a value or data, and it may or may not have a child node.
Understanding the vocabulary is the first step to mastering trees.
!Tree Terminology Diagram
N nodes will always have N-1 edges.A common way to implement a generic tree is to create a TreeNode class. Each node will contain its data and a list of its children.
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self.children.append(child)
--- Usage ---
root = TreeNode("Electronics")
laptop = TreeNode("Laptop")
laptop.add_child(TreeNode("Macbook"))
laptop.add_child(TreeNode("Surface"))
cellphone = TreeNode("Cell Phone")
cellphone.add_child(TreeNode("iPhone"))
cellphone.add_child(TreeNode("Google Pixel"))
root.add_child(laptop)
root.add_child(cellphone)
print("The root node is:", root.data)
print("Its children are:", [child.data for child in root.children])
print("The parent of 'Macbook' is:", laptop.data)
There are many types of trees, each with specific properties and use cases. In the upcoming chapters, we will focus on the most common and important type:
Trees are fundamental in computer science, used in everything from file systems and databases to AI and graphics.