Trees
BST Insert
Insert values into a binary search tree by comparing at each node.
Algorithm
The canonical tree is 4(2(1,3),6(5,7)), so this Python DSA
implementation can be compared directly with the rest of the DSA track.
Basic Implementation
basic.py
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def render(node):
if node is None:
return "_"
if node.left is None and node.right is None:
return str(node.value)
return f"{node.value}({render(node.left)},{render(node.right)})"
def sample_tree():
n1 = Node(1)
n3 = Node(3)
n2 = Node(2, n1, n3)
n5 = Node(5)
n7 = Node(7)
n6 = Node(6, n5, n7)
return Node(4, n2, n6)
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
root = None
for value in [4, 2, 6, 1, 3, 5, 7]:
root = insert(root, value)
print(render(root))
Complexity
- Time: O(h) per insert
- Space: O(n)
Implementation notes
- Render tree structure explicitly instead of printing node objects.
- The replay highlights the node, traversal state, queue, path, or search cursor that changes at each step.
binary search tree
Values smaller than a node go left; larger values go right.