Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 49fe944

Browse files
Merge pull request fnplus#436 from SubCoder1/master
Binary Search Tree implementation in Python
2 parents 0c9565f + 9f3e4df commit 49fe944

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class Node:
2+
def __init__(self, value):
3+
self.value = value
4+
self.left, self.right = None, None
5+
6+
def get_left_child(self):
7+
return self.left
8+
9+
def get_right_child(self):
10+
return self.right
11+
12+
class BinarySearchTree:
13+
def __init__(self):
14+
self.root = None
15+
16+
def insert_into_tree(self, value):
17+
newNode = Node(value=value)
18+
if self.root is None:
19+
self.root = newNode
20+
else:
21+
root = self.root
22+
while root:
23+
if value < root.value:
24+
if root.left is None:
25+
root.left = newNode
26+
break
27+
else:
28+
root = root.left
29+
else:
30+
if root.right is None:
31+
root.right = newNode
32+
break
33+
else:
34+
root = root.right
35+
36+
def search_in_tree(self,value):
37+
if self.root is None:
38+
return f'value({value}) not found'
39+
elif self.root.value == value:
40+
return f'value({value}) found in root'
41+
else:
42+
root = self.root
43+
while root:
44+
if value == root.value:
45+
return f'value({value}) found in tree'
46+
elif value < root.value:
47+
if root.left is None:
48+
return f'value({value}) not found'
49+
else:
50+
root = root.left
51+
else:
52+
if root.right is None:
53+
return f'value({value}) not found'
54+
else:
55+
root = root.right
56+
57+
def inorder_traversal(self, root):
58+
if root:
59+
self.inorder_traversal(root.left)
60+
print(root.value, ' -> ', end='')
61+
self.inorder_traversal(root.right)
62+
63+
if __name__ == '__main__':
64+
# Initializing a Binary Search Tree
65+
BST = BinarySearchTree()
66+
# Inserting into the tree in a BST fashion
67+
BST.insert_into_tree(value=190)
68+
BST.insert_into_tree(value=14)
69+
BST.insert_into_tree(value=199)
70+
BST.insert_into_tree(value=3)
71+
# Inorder traversal of the tree
72+
BST.inorder_traversal(root=BST.root)
73+
print() # Just for a newline :)
74+
# Searching for a value in the tree
75+
print(BST.search_in_tree(value=12))
76+
print(BST.search_in_tree(value=14))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /