-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.py
executable file
·99 lines (77 loc) · 2.59 KB
/
BST.py
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
92
93
94
95
96
97
98
99
#!/usr/bin/env python
class BST_Node:
def __init__(self, payload, parent = None, left_child = None, right_child = None):
self.payload = payload
self.parent = parent
self.left_child = left_child
self.right_child = right_child
def get_payload(self):
return self.payload
def get_left_child(self):
return self.left_child
def get_right_child(self):
return self.right_child
def get_parent(self):
return self.parent
def set_payload(self, payload):
self.payload = payload
def set_left_child(self, child):
self.left_child = child
def set_right_child(self, child):
self.right_child = child
def set_parent(self, parent):
self.parent = parent
def has_right_child(self):
if self.right_child == None:
return False
return True
def has_left_child(self):
if self.left_child == None:
return False
return True
def has_parent(self):
if self.parent == None:
return False
return True
class BST:
def __init__(self):
self.head = None
def put(self, data, current_node):
if data < current_node.get_payload():
if current_node.has_left_child():
self.put(data, current_node.get_left_child())
else:
newNode = BST_Node(data)
newNode.set_parent(current_node)
current_node.set_left_child(newNode)
elif data > current_node.get_payload():
if current_node.has_right_child():
self.put(data, current_node.get_right_child())
else:
newNode = BST_Node(data)
newNode.set_parent(current_node)
current_node.set_right_child(newNode)
def add(self,data):
newNode = BST_Node(data)
if self.head == None:
self.head = newNode
else:
current_node = self.head
self.put(data,current_node)
def print_list_ascending(self):
self._print_list_ascending(self.head)
def _print_list_ascending(self, current_node):
if current_node == None:
return
else:
if current_node.has_left_child():
self._print_list_ascending(current_node.get_left_child())
print current_node.get_payload(),
if current_node.has_right_child():
self._print_list_ascending(current_node.get_right_child())
bstlist = BST()
bstlist.add(1)
bstlist.add(2)
bstlist.add(0)
bstlist.add(3)
bstlist.print_list_ascending()