-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNode.py
74 lines (56 loc) · 2.14 KB
/
Node.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
# Don't modify __eq__() and other relational methods, because method delete() in BinarySearchTree class might mind this!
# It uses != to see if the two objects are the same object, not if they just have the same key.
class Node(object):
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.size = 1
def setKey(self, key):
self.key = key
def setParent(self, node):
self.parent = node
def setLeftChild(self, node):
self.left = node
def setRightChild(self, node):
self.right = node
def setSize(self, size):
self.size = size
def incrementSize(self):
self.size += 1
def decrementSize(self):
self.size -= 1
def recomputeSize(self):
left, right = self.left, self.right
if left:
leftSize = left.getSize()
else:
leftSize = 0
if right:
rightSize = right.getSize()
else:
rightSize = 0
self.size = leftSize + rightSize + 1
def getKey(self):
return self.key
def getParent(self):
return self.parent
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def getSize(self):
return self.size
def printNode(self):
print("Key: {}, Parent: {}, Left child: {}, Right child: {}, Size: {}".format(self.key, self.parent, self.left, self.right, self.size))
def __str__(self):
return str(self.key)
def __repr__(self):
"""This can be used as:
print(repr(tree.find(key, root)))
But, it's also very useful for debugging, because debugger will show us the key of the node without the need for expanding the node.
Of course, we can add some other pieces of information, too.
We can return "str(self.key)" and concatenate other string to it, or we can use the form below. Anyhow, we must return a string.
"""
return "Key: {}, Size: {}".format(self.key, self.size)