Python Trees


A tree is one of the most important data structures used in computer science. It helps you organize data in a parent-child relationship instead of a simple linear order. Trees are used in file systems, organization charts, search engines, databases, compilers and many other applications where you need structured and hierarchical data. A tree starts from a root node, and every node can have zero or more child nodes. This structure makes searching, inserting and managing data efficient and predictable.

In this tutorial, you will learn what trees are, how nodes are connected, different types of trees, how to build tree nodes in Python and how traversal methods work. You will also learn how real systems use trees and get several practical examples that help strengthen your understanding.

What Is a Tree?

A tree is a non-linear data structure made up of nodes. Each node contains:

  • A value

  • A reference to its children

The top-most node is called the root. Every node except the root has one parent. Nodes with no children are called leaves.

A tree looks like this:

        Root
        /  \
      A      B
     / \    / \
    C   D  E   F

This style of structure helps when storing layered information like categories, directories and decision paths.

Key Terms in a Tree

Before you start building trees, it helps to understand common terminology.

Root

The first node in the tree.

Parent

A node that has one or more children.

Child

A node that comes under a parent.

Leaf Node

A node with no children.

Sibling

Nodes that share the same parent.

Depth

Distance from the root to a node.

Height

Longest path from a node down to its leaf.

Knowing these terms makes it easier to understand advanced operations.

Why Trees Are Important

Trees are fast for searching and organizing information. They help in:

  • File directories

  • AI decision-making

  • Syntax parsing

  • Hierarchical data representing

  • Search algorithms

  • Database indexing

Their flexible structure allows branching, which linear structures cannot provide.

Types of Trees

There are many types of trees in DSA. Some important ones include:

General Tree

Each node can have any number of children.

Binary Tree

Each node has at most two children.

Binary Search Tree

Left child is smaller, right child is larger.

AVL Tree

A self-balancing tree.

Heap

Complete tree used in priority queues.

Trie

Used in text searching and autocomplete.

In this chapter, you will focus on basic trees and how to implement them in Python.

Creating a Simple Tree Node Class

You can represent a tree node using a Python class:

class Node:
    def __init__(self, value):
        self.value = value
        self.children = []

This lets each node store its children in a list.

Adding children:

root = Node("Root")
child1 = Node("A")
child2 = Node("B")

root.children.append(child1)
root.children.append(child2)

This creates a simple structure.

Printing a Tree Structure

You can print the tree in a readable form using recursion:

def print_tree(node, level=0):
    print(" " * level * 2 + node.value)
    for child in node.children:
        print_tree(child, level + 1)

Calling:

print_tree(root)

This displays the entire hierarchy.

Tree Traversal Methods

Traversal means visiting every node in a specific order. There are three common ways to traverse a tree.

Preorder Traversal

Visit current node first, then children.

def preorder(node):
    if not node:
        return
    print(node.value)
    for child in node.children:
        preorder(child)

Postorder Traversal

Visit children first, then current node.

def postorder(node):
    if not node:
        return
    for child in node.children:
        postorder(child)
    print(node.value)

These two methods are common in general trees.

Level Order Traversal (Breadth-First)

This traversal visits nodes level by level.

from collections import deque

def level_order(root):
    queue = deque([root])
    while queue:
        node = queue.popleft()
        print(node.value)
        for child in node.children:
            queue.append(child)

This method is useful for features like shortest path finding.

Real-Life Uses of Trees

File Systems

Folders and files are stored as a tree.

Organization Hierarchy

CEO → Managers → Team leads → Staff

Category Menus

E-commerce websites display nested categories using trees.

HTML Document Structure

Every tag forms a tree-like layout.

AI Decision Trees

Games and predictive models use trees to choose the best action.

Trees appear in many everyday systems around you.

Building a Simple Category Tree

root = Node("Electronics")

phone = Node("Mobiles")
laptop = Node("Laptops")
tv = Node("Television")

root.children.append(phone)
root.children.append(laptop)
root.children.append(tv)

print_tree(root)

Shows categories in a structured form.

Tree Simulation: Company Structure

ceo = Node("CEO")
manager1 = Node("Manager A")
manager2 = Node("Manager B")

ceo.children.append(manager1)
ceo.children.append(manager2)

manager1.children.append(Node("Team Lead 1"))
manager2.children.append(Node("Team Lead 2"))

print_tree(ceo)

This is how organizations visualize teams.

Practical Examples

Example 1: Create a node

node = Node("Hello")

Example 2: Add child nodes

node.children.append(Node("Child"))

Example 3: Build a small tree

root = Node("Root")
root.children.append(Node("A"))

Example 4: Preorder traversal

preorder(root)

Example 5: Postorder traversal

postorder(root)

Example 6: Level order traversal

level_order(root)

Example 7: Print structure

print_tree(root)

Example 8: Create multi-level tree

child = Node("X")
child.children.append(Node("Y"))
root.children.append(child)

Example 9: Tree for menu system

menu = Node("Menu")
menu.children.append(Node("Home"))
menu.children.append(Node("Products"))

Example 10: Tree as directory system

folder = Node("Documents")
folder.children.append(Node("Projects"))
folder.children.append(Node("Photos"))

Summary of the Tutorial

A tree is a hierarchical structure made up of nodes connected through parent-child relationships. You learned about roots, children, leaves, depth, height, and different tree types. You also learned how to build trees using a Python class, print them recursively and traverse them using preorder, postorder and level order techniques. Trees form the backbone of file systems, organizations, decision-making models, search engines and many advanced algorithms. With this foundation, you are ready to explore more structured trees like binary trees and binary search trees.


Practice Questions

Q1. Write a Python program to create a binary tree with root = 1 and two children 2 (left) and 3 (right).

Q2. Write a Python program to print all elements of the binary tree using Inorder traversal.

Q3. Write a Python program to count the total number of nodes in the binary tree.

Q4. Write a Python program to find the maximum value stored in the binary tree.

Q5. Write a Python program to add a new node to the left of a given node.

Q6. Write a Python program to traverse the binary tree using Postorder traversal.

Q7. Write a Python program to check if a binary tree is empty.

Q8. Write a Python program to find and print all leaf nodes of the binary tree.

Q9. Write a Python program to search for a specific value in the binary tree.

Q10. Write a Python program to convert a list of values into a binary tree structure (level-wise).


Go Back Top