Binary Search Tree - Insertion (Python)
suggest changeThis 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)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents