How Can I Implement a Tree in Python?

Understand how to implement a tree in Python using classes and recursion. Includes code examples for basic node creation and building parent-child structures.

A tree is a hierarchical data structure used to represent relationships like file systems, organization charts or DOM elements. Python doesn’t have a built-in tree data type but you can easily implement one using classes. Here are two easy ways to implement trees in Python:

Method 1: Using Simple Class-Based Tree

A basic approach using custom classes to define nodes and children.

Step 1: Define a Node Class

A reusable structure for each node in the tree, including data and child references.
class TreeNode:    def __init__(self, data):         self.data = data         self.children = []       def add_child(self, node):         self.children.append(node)       def print_tree(self, level=0):         print('  ' * level + str(self.data))         for child in self.children:             child.print_tree(level + 1)

Step 2: Create the Tree Structure

Builds the tree by connecting parent and child nodes by using the add_child() method.
# Create root and child nodesroot = TreeNode("Electronics") laptop = TreeNode("Laptop") phone = TreeNode("Phone")   root.add_child(laptop) root.add_child(phone)   laptop.add_child(TreeNode("MacBook")) laptop.add_child(TreeNode("ThinkPad"))   phone.add_child(TreeNode("iPhone")) phone.add_child(TreeNode("Samsung"))   # Print the tree root.print_tree()
Output:
Electronics  Laptop     MacBook     ThinkPad   Phone     iPhone     Samsung
This is good for general purpose tree structures in a readable and recursive format.
Also Read: Python Developer Hourly Rate in 2025

Method 2: Using Dictionaries for Lightweight Trees

Use nested dictionaries for simple key-value based trees.
tree = {    "Electronics": {         "Laptop": {             "MacBook": {},             "ThinkPad": {}         },         "Phone": {             "iPhone": {},             "Samsung": {}         }     } }
This is useful for static trees, JSON serialization or quick lookups.

Tip

  • Use classes for dynamic, object oriented tree manipulation.
  • Use dictionaries when you need quick and lightweight structures—especially for config-like or serialized trees.
  • Consider third party libraries like anytree if you need advanced features like tree traversal or exporting.
Related

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025

Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using…

10 Oct, 2025

These are the typical reasons why the conda command fails and practical steps to fix them across Windows, macOS and Linux environments. Here are some…

07 Oct, 2025
Request a Quote Schedule a Meeting