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.

Summarize with AI

Not enough time? get the key points instantly.

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.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

How to Copy Files in Python

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…