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.

Also Read:

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.