Tree Data Structure: Definition, Example, and Uses
tree data structure is a way to organize data in a hierarchy, like a family tree, where each item (called a node) can have child nodes connected below it. It starts from a single root node and branches out, making it easy to represent relationships and organize information.How It Works
Imagine a tree in nature: it has a main trunk and many branches that split off. A tree data structure works similarly. It starts with one main item called the root. From this root, there are branches to other items called child nodes. Each child can have its own children, creating a branching structure.
This structure helps organize data where relationships matter, like a family tree showing parents and children or a folder system on your computer where folders contain subfolders. Each node connects to others in a clear, one-way path from the root down to leaves (nodes with no children).
Example
This example shows a simple tree with a root and two children. It prints each node's value in order.
class Node: def __init__(self, value): self.value = value self.children = [] def add_child(self, child_node): self.children.append(child_node) def print_tree(self, level=0): print(' ' * level + str(self.value)) for child in self.children: child.print_tree(level + 1) # Create root node root = Node('Root') # Create children child1 = Node('Child 1') child2 = Node('Child 2') # Add children to root root.add_child(child1) root.add_child(child2) # Add a child to one of the children child1.add_child(Node('Grandchild 1')) # Print the tree root.print_tree()
When to Use
Use a tree data structure when you need to represent data with a clear hierarchy or parent-child relationships. Common uses include:
- Organizing files and folders on a computer
- Representing family trees or organizational charts
- Managing data in databases with hierarchical relationships
- Building menus or navigation systems in apps and websites
- Parsing expressions or syntax in programming languages
Trees help quickly find, add, or remove items while keeping the structure easy to understand.
Key Points
- A tree starts with one root node and branches out to child nodes.
- Each node can have zero or more children, but only one parent.
- Leaves are nodes without children, at the ends of branches.
- Trees are useful for hierarchical data and fast searching.