Skip to content

Add Binary Search Tree in data_structures #84

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

Merged
merged 8 commits into from
Jun 21, 2017
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,4 @@ ENV/
# Rope project settings
.ropeproject
.idea
.DS_Store
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ install:
- if [ "$TRAVIS_PYTHON_VERSION" == "3.2" ]; then travis_retry pip install coverage==3.7.1; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "3.2" ]; then travis_retry pip install coverage; fi
- "pip install pytest pytest-cov"
script: py.test --doctest-modules --cov ./
script: py.test --doctest-modules --cov ./
101 changes: 101 additions & 0 deletions data_structures/Binary Tree/binary_seach_tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
'''
A binary search Tree
'''
class Node:

def __init__(self, label):
self.label = label
self.left = None
self.rigt = None

def getLabel(self):
return self.label

def setLabel(self, label):
self.label = label

def getLeft(self):
return self.left

def setLeft(self, left):
self.left = left

def getRight(self):
return self.rigt

def setRight(self, right):
self.rigt = right


class BinarySearchTree:

def __init__(self):
self.root = None

def insert(self, label):

#Create a new Node

node = Node(label)

if self.empty():
self.root = node
else:
dad_node = None
curr_node = self.root

while True:
if curr_node != None:

dad_node = curr_node

if node.getLabel() < curr_node.getLabel():
curr_node = curr_node.getLeft()
else:
curr_node = curr_node.getRight()
else:
if node.getLabel() < dad_node.getLabel():
dad_node.setLeft(node)
else:
dad_node.setRight(node)
break

def empty(self):
if self.root == None:
return True
return False

def preShow(self, curr_node):
if curr_node != None:
print(curr_node.getLabel(), end=" ")

self.preShow(curr_node.getLeft())
self.preShow(curr_node.getRight())

def getRoot(self):
return self.root


'''
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
'''

t = BinarySearchTree()
t.insert(8)
t.insert(3)
t.insert(1)
t.insert(6)
t.insert(4)
t.insert(7)
t.insert(10)
t.insert(14)
t.insert(13)

t.preShow(t.getRoot())