Binary Search Tree - Insertion (Python)

suggest change

This is a simple binary-search-tree insertion implementation in modern Python. Duplicate values are inserted into the right subtree.

An example is shown below:

Following the code snippet each image shows the execution visualization which makes it easier to visualize how this code works.

from dataclasses import dataclass


@dataclass
class Node:
    data: int
    left: "Node | None" = None
    right: "Node | None" = None

def insert(root: Node | None, node: Node) -> Node:
    if root is None:
        return node

    if node.data < root.data:
        root.left = insert(root.left, node)
    else:
        root.right = insert(root.right, node)
    return root

def in_order_print(root: Node | None) -> None:
    if root is None:
        return
    in_order_print(root.left)
    print(root.data)
    in_order_print(root.right)

def pre_order_print(root: Node | None) -> None:
    if root is None:
        return
    print(root.data)
    pre_order_print(root.left)
    pre_order_print(root.right)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents