Last active
June 24, 2018 10:45
-
-
Save RusEu/6b871370a4be786503507160508a1219 to your computer and use it in GitHub Desktop.
Binary Search Tree
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, value=None): | |
self.left_child = None | |
self.right_child = None | |
self.value = value | |
class BST(): | |
def __init__(self): | |
self.root = Node() | |
def insert(self, value): | |
"""Insert a new value in the tree""" | |
if not self.root.value: | |
self.root.value = value | |
else: | |
self._insert(node=self.root, value=value) | |
def _insert(self, node, value): | |
"""Populate the tree with nodes""" | |
if value < node.value: | |
if node.left_child: | |
self._insert(node.left_child, value) | |
else: | |
node.left_child = Node(value=value) | |
elif value > node.value: | |
if node.right_child: | |
self._insert(node.right_child, value) | |
else: | |
node.right_child = Node(value=value) | |
def find(self, value): | |
"""Find by value""" | |
if not self.root: | |
return False | |
return self._find(self.root, value) | |
def _find(self, node, value): | |
"""Find by node""" | |
if node.value == value: | |
return True | |
if value < node.value: | |
if node.left_child: | |
return self._find(node.left_child, value) | |
return False | |
elif value > node.value: | |
if node.right_child: | |
return self._find(node.right_child, value) | |
return False | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment