-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_tree.py
More file actions
66 lines (57 loc) · 1.63 KB
/
binary_search_tree.py
File metadata and controls
66 lines (57 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self) -> None:
self.root = None
def _insert_recursive(self, data, root):
if data['id'] < root.data['id']:
if root.left is None:
root.left = Node(data)
else:
self._insert_recursive(data, root.left)
elif data['id'] > root.data['id']:
if root.right is None:
root.right = Node(data)
else:
self._insert_recursive(data, root.right)
else:
return
def insert(self, data):
if self.root is None:
self.root = Node(data)
else:
self._insert_recursive(data, self.root)
def search_blog(self, blog_id):
return self.search(int(blog_id), self.root)
def search(self, id, node):
if node is None:
return False
if node.data['id'] is id:
return node.data
else:
if id < node.data['id']:
return self.search(id, node.left)
elif id > node.data['id']:
return self.search(id, node.right)
else:
return False
if __name__ == "__main__":
bst = BST()
d = {
"body": "Hello world",
"id": 6,
"title": "Century share visit phone should could.",
"user_id": 42
}
d1 = {
"body": "Hello moon",
"id": 2,
"title": " visit phone should could.",
"user_id": 2
}
bst.insert(d)
bst.insert(d1)
print(bst.search_blog(2))