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 3eb8b06

Browse files
Added Binary Search Tree python implementation
1 parent a081caa commit 3eb8b06

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
root = self.root
19+
if root is None:
20+
self.root = newNode
21+
else:
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+
37+
def inorder_traversal(self, root):
38+
if root:
39+
self.inorder_traversal(root.left)
40+
print(root.value, ' -> ', end='')
41+
self.inorder_traversal(root.right)
42+
43+
if __name__ == '__main__':
44+
# Initializing a Binary Search Tree
45+
BST = BinarySearchTree()
46+
# Inserting into the tree in a BST fashion
47+
BST.insert_into_tree(value=190)
48+
BST.insert_into_tree(value=14)
49+
BST.insert_into_tree(value=199)
50+
BST.insert_into_tree(value=3)
51+
# Inorder traversal of the tree
52+
BST.inorder_traversal(root=BST.root)

0 commit comments

Comments
(0)

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