Skip to content

Instantly share code, notes, and snippets.

@jonaed1230
Created September 16, 2018 17:33
Show Gist options
  • Save jonaed1230/8cd80b6d710a177608cc0eeb084b67ab to your computer and use it in GitHub Desktop.
Save jonaed1230/8cd80b6d710a177608cc0eeb084b67ab to your computer and use it in GitHub Desktop.
Searching elements in tree
def bst_insert(root, node):
last_node = None
current_node = root
while current_node is not None:
last_node = current_node
if node.data < current_node.data:
current_node = current_node.left
else:
current_node = current_node.right
if last_node is None:
# tree was empty, node is the only node, hence root
root = node
elif node.data < last_node.data:
last_node.add_right(node)
else:
last_node.add_right(node)
return root
class TreeNode:
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
if node is not None:
node.parent = self
def add_right(self, node):
self.right = node
if node is not None:
node.parent = self
def bst_insert(root, node):
# আগের কোডের মতো হবে
"""
_10_
/ \
5 17
/ \ / \
3 7 12 19
/ \
1 4
"""
def create_bst():
ten = TreeNode(10)
five = TreeNode(5)
seventeen = TreeNode(17)
ten.add_left(five)
ten.add_right(seventeen)
three = TreeNode(3)
seven = TreeNode(7)
five.add_left(three)
five.add_right(seven)
one = TreeNode(1)
four = TreeNode(4)
three.add_left(one)
three.add_right(four)
twelve = TreeNode(12)
nineteen = TreeNode(19)
seventeen.add_left(twelve)
seventeen.add_right(nineteen)
# now return to the root node
return ten
if __name__ == "__main__":
root = create_bst()
print(root)
# searching function for binary tree
def bst_search(node, key):
while node is not None:
if node.data == key:
return node
if key < node.data:
node = node.left
else:
node = node.right
return node
if __name__ == "__main__":
root = create_bst()
for key in [7, 8]:
print("searching", key)
result = bst_search(root, key)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment