Programming & Development / April 19, 2025

Trees in Python: Traversals, Insertion, and Deletion Explained

trees binary tree python data structures in-order traversal pre-order traversal post-order traversal insert node delete node dfs tree operations interview prep

Tree data structures are a core concept in computer science, especially in algorithms and system design. In Python, binary trees are commonly used and can be implemented using classes and recursion.

๐ŸŒณ Binary Tree Basics

Each node contains:

  • A value
  • A left child
  • A right child

๐Ÿงฑ Node Definition

python

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

๐Ÿ” Tree Traversals

1. ๐ŸŒฟ In-Order Traversal (Left, Root, Right)

python

def in_order(root):
    if root:
        in_order(root.left)
        print(root.value, end=" ")
        in_order(root.right)

2. ๐ŸŒฒ Pre-Order Traversal (Root, Left, Right)

python

def pre_order(root):
    if root:
        print(root.value, end=" ")
        pre_order(root.left)
        pre_order(root.right)

3. ๐Ÿ‚ Post-Order Traversal (Left, Right, Root)

python

def post_order(root):
    if root:
        post_order(root.left)
        post_order(root.right)
        print(root.value, end=" ")

โž• Insertion in Binary Search Tree (BST)

python

def insert(root, value):
    if root is None:
        return TreeNode(value)
    if value < root.value:
        root.left = insert(root.left, value)
    else:
        root.right = insert(root.right, value)
    return root

โŒ Deletion in Binary Search Tree (BST)

python

def delete(root, value):
    if not root:
        return root
    if value < root.value:
        root.left = delete(root.left, value)
    elif value > root.value:
        root.right = delete(root.right, value)
    else:
        # Node with only one child or no child
        if not root.left:
            return root.right
        elif not root.right:
            return root.left
        # Node with two children
        min_larger_node = get_min(root.right)
        root.value = min_larger_node.value
        root.right = delete(root.right, min_larger_node.value)
    return root

def get_min(node):
    while node.left:
        node = node.left
    return node

๐Ÿงช Sample Usage

python

root = None
values = [50, 30, 20, 40, 70, 60, 80]
for val in values:
    root = insert(root, val)

print("In-order: ")
in_order(root)
print("\nDeleting 20...")
root = delete(root, 20)
print("In-order after deletion: ")
in_order(root)

๐Ÿ“ Summary

OperationDescriptionIn-OrderLeft โ†’ Root โ†’ RightPre-OrderRoot โ†’ Left โ†’ RightPost-OrderLeft โ†’ Right โ†’ RootInsertionAdds a value while maintaining BST propertyDeletionHandles all three deletion cases

Understanding tree operations like these is essential for solving problems in recursion, search optimization, and hierarchical data representation.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex