Skip to content

Commit

Permalink
add insert function
Browse files Browse the repository at this point in the history
  • Loading branch information
kuo4230 committed Jan 18, 2025
1 parent 69ee212 commit 25cec35
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/datastructpy/non_linear/trees/binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from datastructpy.node import Node


class BinarySearchTree:
"""
A class representing a binary search tree (BST).
Expand Down Expand Up @@ -50,7 +53,29 @@ def insert(self, key):
print(bst.root.left.key) # Output: 5
print(bst.root.right.key) # Output: 15
"""

if self.root is None:
self.root = Node(key)
else:
current = self.root
while True:
if key < current.key:
# Go to the left subtree
if current.left is None:
current.left = Node(key)
break
else:
current = current.left
elif key > current.key:
# Go to the right subtree
if current.right is None:
current.right = Node(key)
break
else:
current = current.right
else:
# The key is already in the BST (no duplicates allowed)
break

def search(self, key):
"""
Checks if a value exists in the Binary Search Tree (BST).
Expand Down

0 comments on commit 25cec35

Please sign in to comment.