Skip to content

Create binary search tree #1094

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions exercises/binary-search-tree/bst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# A binary search tree implementation


class Node:

def __init__(self, data=0, left=None, right=None):
# initialize node data
self.left = None
self.right = None
self.data = data


class BST:
def __init__(self):
# initialize the root node
self.root = None

def add_node(self, data):
# Returns a new node initialized with data
return Node(data)

def insert(self, root, data):

if root is None: # Tree is empty
return self.add_node(data)
else:
# Modifying the tree
if data <= root.data:
root.left = self.insert(root.left, data)
else:
root.right = self.insert(root.right, data)
return root

def search(self, root, target):

if root is None:
return 0
else:
if target == root.data:
return 1
else:
if target < root.data:
return self.search(root.left, target)
else:
return self.search(root.right, target)

def min_value(self, root):
while root.left is not None:
root = root.left
return root.data

def max_value(self, root):
while root.right is not None:
root = root.right
return root.data

def size(self, root):
if root is None:
return 0
else:
return self.size(root.left) + self.size(root.right) + 1