0
0
PythonHow-ToBeginner · 3 min read

How to Implement Binary Tree in Python: Simple Guide

To implement a binary tree in Python, define a Node class with attributes for value, left, and right child nodes. Then create instances of this class to build the tree structure by linking nodes through their left and right attributes.
📐

Syntax

The basic syntax involves creating a Node class with three parts: value to store data, left for the left child node, and right for the right child node. Each node can link to two children or none if it is a leaf.

python
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
💻

Example

This example shows how to create a simple binary tree with a root and two children, then print the root and its children values.

python
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

# Create nodes
root = Node(10)
root.left = Node(5)
root.right = Node(15)

# Print values
print('Root:', root.value)
print('Left child:', root.left.value)
print('Right child:', root.right.value)
Output
Root: 10 Left child: 5 Right child: 15
⚠️

Common Pitfalls

Common mistakes include forgetting to initialize left and right as None, which can cause errors when accessing child nodes. Another pitfall is mixing up left and right children when linking nodes, which changes the tree structure unexpectedly.

Also, avoid using mutable default arguments in the constructor, as it can cause shared state between nodes.

python
class NodeWrong:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

# Wrong: mutable default argument example (if used with lists or dicts)

# Correct way is to use None and assign inside the method as shown in the Syntax section.
📊

Quick Reference

Remember these tips when implementing a binary tree:

  • Each node stores a value and links to left and right children.
  • Initialize children as None if no child exists.
  • Build the tree by linking nodes through their left and right attributes.
  • Use clear naming to avoid confusion between left and right.

Key Takeaways

Define a Node class with value, left, and right attributes to represent each tree node.
Initialize left and right children as None to indicate no child nodes.
Link nodes by assigning Node instances to left and right attributes to build the tree.
Avoid mutable default arguments in constructors to prevent shared state bugs.
Double-check left and right assignments to maintain correct tree structure.