-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (71 loc) · 2.29 KB
/
Copy pathmain.py
File metadata and controls
92 lines (71 loc) · 2.29 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Tree:
def __init__(self):
self.root = None
def search(self, value):
found_node = self._search(self.root, value)
if found_node is None:
return False
return True
def delete(self, value):
pass
def max_value(self):
pass
def min_value(self):
pass
def insert(self, value):
if self.root is None:
self.root = Node(value)
return
return self._insert(self.root, value)
# def _insert_with_search(self,value):
# found_node = self._search(self.root, value)
# scenario 1 - no such value in tree
# found_node.parent
def _insert(self, current_node, value):
# go to right
if value > current_node.value:
# add right leaf if absent
if current_node.right is None:
current_node.right = Node(value, current_node)
return
# search for a proper position in right branch
return self._insert(current_node.right, value)
else:
# add left leaf if absent
if current_node.left is None:
current_node.left = Node(value, current_node)
return
return self._insert(current_node.left, value)
def _search(self, node_to_check, value):
# no more nodes, our parent is a leaf
# we found: searched value is equal to the node
if (node_to_check is None) or (node_to_check.value == value):
return node_to_check
if value > node_to_check.value:
# go right
return self._search(node_to_check.right, value)
else:
# go left
return self._search(node_to_check.left, value)
def PrintTree(self, root):
arr = []
if root:
arr.append(root.value)
arr = arr + self.PrintTree(root.left)
arr = arr + self.PrintTree(root.right)
return arr
class Node:
def __init__(self, value, parent=None):
self.right = None
self.left = None
self.parent = None
self.value = value
tree = Tree()
tree.insert(10)
tree.insert(6)
tree.insert(8)
tree.insert(4)
print(tree.search(10))
print(tree.search(8))
print(tree.search(6))
print(tree.PrintTree(tree.root))