Created
November 27, 2018 03:08
-
-
Save yeaske/4e5f3b12ed0df158fd1d1addef84b36d to your computer and use it in GitHub Desktop.
Binary Tree in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, data): | |
self.data = data | |
self.left, self.right = None, None | |
def __str__(self): | |
return str(self.data) | |
def insert(self, data): | |
if self.data: | |
if data < self.data: | |
if self.left: | |
self.left.insert(data) | |
else: | |
self.left = Node(data) | |
elif data > self.data: | |
if self.right: | |
self.right.insert(data) | |
else: | |
self.right = Node(data) | |
else: | |
# print('Data already exists') | |
pass | |
else: | |
self.data = data | |
def display_tree(self): | |
if self.left: | |
self.left.display_tree() | |
print(self.data) | |
if self.right: | |
self.right.display_tree() | |
def find_value(self, val): | |
if val == self.data: | |
print('Found value') | |
elif val < self.data: | |
if self.left: | |
self.left.find_value(val) | |
else: | |
print('Not found') | |
elif val > self.data: | |
if self.right: | |
self.right.find_value(val) | |
else: | |
print('Not found') | |
if __name__ == '__main__': | |
root = Node(22) | |
root.insert(15) | |
root.insert(123) | |
root.insert(11) | |
root.insert(11) | |
root.insert(1) | |
root.insert(33) | |
root.insert(88) | |
root.insert(8) | |
root.insert(146) | |
root.display_tree() | |
root.find_value(1) | |
root.find_value(32) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment