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 9f3e4df

Browse files
added search function in B_S_T.py
1 parent c7a9d48 commit 9f3e4df

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

‎Algorithms/Tree/Binary Search Tree/Python/B_S_T.py‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ def __init__(self):
1515

1616
def insert_into_tree(self, value):
1717
newNode = Node(value=value)
18-
root = self.root
19-
if root is None:
18+
if self.root is None:
2019
self.root = newNode
2120
else:
21+
root = self.root
2222
while root:
2323
if value < root.value:
2424
if root.left is None:
@@ -32,7 +32,27 @@ def insert_into_tree(self, value):
3232
break
3333
else:
3434
root = root.right
35-
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
3656

3757
def inorder_traversal(self, root):
3858
if root:
@@ -49,4 +69,8 @@ def inorder_traversal(self, root):
4969
BST.insert_into_tree(value=199)
5070
BST.insert_into_tree(value=3)
5171
# Inorder traversal of the tree
52-
BST.inorder_traversal(root=BST.root)
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 によって変換されたページ (->オリジナル) /