Back to Python
2026-02-156 min read

Binary Trees (Python Programming)

Learn Binary Trees (Python Programming) step by step with clear examples and exercises.

Title: Python Binary Trees - A full guide for Practical Depth

Why This Matters

Binary trees are a fundamental data structure used in computer science to efficiently store and retrieve data. They are essential for various real-world applications, including parsing expressions, sorting, and database indexing. Understanding binary trees can help you solve complex problems, debug errors in your code, and prepare for interviews and exams.

A well-structured binary tree allows for efficient search, insertion, deletion, and traversal operations. This makes them ideal for handling large datasets and optimizing algorithms. Moreover, binary trees provide a foundation for understanding more complex data structures like AVL trees, Red-Black trees, and B-trees.

Prerequisites

Before diving into binary trees, it is crucial to have a good understanding of Python programming concepts such as variables, functions, loops, recursion, and data structures like lists and arrays. Familiarity with basic tree terminology (root, node, leaf, parent, child, sibling) will also be helpful.

It's recommended to review essential topics like arrays and linked lists as they provide a foundation for understanding binary trees. Additionally, having experience with recursion is crucial since many operations on binary trees are performed using recursive functions.

Core Concept

A binary tree is a tree data structure in which each node has at most two children called the left child and right child. The node without any children is known as a leaf. The node at the top of the tree is called the root. Binary trees can be either empty or non-empty.

Binary trees are classified into two types:

  1. Complete binary tree: A complete binary tree is a binary tree in which all levels, except possibly the last level, are completely filled, and all nodes in the last level are as far left as possible.
  2. Perfect binary tree: A perfect binary tree is a complete binary tree where all internal nodes have exactly two children, and all leaves are at the same depth.

Tree Traversals

There are three main ways to traverse a binary tree: Inorder, Preorder, and Postorder. Each traversal method has its use cases and is essential for various operations on binary trees.

  1. Inorder Traversal: Visit left subtree, visit the node, then visit the right subtree. This order results in an output that is sorted in ascending order if the tree represents a sorted set of values. Inorder traversal can be used to find the minimum and maximum values in a binary search tree.
  2. Preorder Traversal: Visit the node, then traverse the left subtree, and finally traverse the right subtree. Preorder traversal is often used for constructing binary trees from given data or when you want to process the node before its children. It can be useful in serializing a tree into a string representation.
  3. Postorder Traversal: Traverse the left subtree, traverse the right subtree, then visit the node. Postorder traversal is useful for tasks like building expressions from postfix notation or deleting a binary tree without modifying the original order of nodes.

Worked Example

Let's create a simple binary tree to represent an organization chart with employees and their subordinates. Here's the Python code for this example:

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)

In this example, we have created a binary tree with the root node as 1, left child as 2 and right child as 3. The left child of 2 is 4, the right child of 2 is 5, the left child of 3 is 6, and the right child of 3 is 7. This represents an organization structure where employee 1 has two subordinates, employees 2 and 3, who in turn have their own subordinates.

Tree Traversals Example

Here's how you can implement Inorder, Preorder, and Postorder traversals for the above binary tree:

def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)

def preorder(root):
if root:
print(root.val, end=" ")
preorder(root.left)
preorder(root.right)

def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val, end=" ")

Common Mistakes

  1. ### Forgetting to initialize children as None

It's essential to initialize the left and right children of a node as None during creation. Failing to do so can lead to unexpected behavior when accessing or manipulating the tree.

  1. ### Incorrect implementation of inorder, preorder, and postorder traversals

Correctly implementing traversal algorithms is crucial for various operations on binary trees. Common mistakes include using incorrect recursive calls, forgetting base cases, and not handling empty trees properly.

Additional Mistakes

  1. Ignoring edge cases: Be aware of edge cases when writing functions for binary trees. For example, consider what happens when a tree is empty or contains only one node.
  2. Recursion depth limit exceeded: When dealing with very large trees, you may encounter recursion depth limits in Python. To handle this, use iterative solutions or divide-and-conquer strategies to break down the problem into smaller subproblems.
  3. Inefficient implementations: Be mindful of the time and space complexity of your binary tree algorithms. Optimize your code by using efficient data structures and algorithms whenever possible.

Practice Questions

  1. Implement depth-first search (DFS) in a binary tree to find a specific node.
  2. Write a Python function to check if two binary trees are identical.
  3. Given a binary tree, print the nodes at a specific level using Breadth-First Search (BFS).
  4. Implement an iterative version of Morris traversal for inorder, preorder, and postorder traversals.
  5. Write a Python function to find the height of a binary tree recursively and iteratively.
  6. Implement a binary search algorithm on a binary search tree.
  7. Write a Python function to check if a given binary tree is balanced or not.
  8. Given a sorted array, construct a balanced binary search tree using the Minimum Height Balanced Binary Tree (MHBBT) approach.
  9. Implement AVL tree insertion and deletion operations in Python.
  10. Write a Python function to find the common ancestor of two nodes in a binary tree.

FAQ

You can find the height of a binary tree using recursion by calculating the maximum depth of the left and right subtrees plus one (for the root node). Alternatively, you can implement an iterative solution using Breadth-First Search (BFS) to count the number of levels in the tree.

### What is the time complexity of various operations on binary trees?

  • Insertion: O(h), where h is the height of the tree
  • Deletion: O(h) for a balanced tree, O(nh) for an unbalanced tree, where n is the number of nodes
  • Searching: O(h) for a balanced tree, O(n) for an unbalanced tree
  • Traversals (Inorder, Preorder, Postorder): O(n), where n is the number of nodes in the tree

### How do I create a perfect binary tree?

To create a perfect binary tree, ensure that all internal nodes have exactly two children and all leaves are at the same depth. You can achieve this by filling up the left subtree first until it becomes full, then moving to the right subtree.

### What is the difference between a complete binary tree and a perfect binary tree?

A complete binary tree is a binary tree in which all levels, except possibly the last level, are completely filled, and all nodes in the last level are as far left as possible. A perfect binary tree is a complete binary tree where all internal nodes have exactly two children, and all leaves are at the same depth.

### How do I check if a binary tree is complete or not?

To check if a binary tree is complete, traverse the tree using Breadth-First Search (BFS). If any level in the tree has a missing node or more than one node at the end of the level, then the tree is not complete.

Binary Trees (Python Programming) | Python | XQA Learn