forked from sourav-122/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redBlackTree.py
119 lines (79 loc) · 2.92 KB
/
redBlackTree.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class Color:
RED = 1
BLACK = 2
class Node:
def __init__(self, data, parent=None, color=Color.RED) -> None:
self.data = data
self.left_node =None
self.right_node = None
self.parent = parent
self.color = color
class RedBlackTree:
def __init__(self) -> None:
self.root = None
def insert(self, data):
if self.root is None:
self.root = Node(data)
else:
self.insert_node(data, self.root)
def insert_node(self, data, node):
if data < node.data:
if node.left_node:
self.insert_node(data, node.left_node)
else:
node.left_node = Node(data, node)
self.settle_violation(node.left_node)
else:
if node.right_node:
self.insert_node(data, node.right_node)
else:
node.right_node = Node(data, node)
self.settle_violation(node.right_node)
def traverse(self):
if self.root:
self.in_order_traversal(self.root)
def in_order_traversal(self, node):
if node.left:
self.in_order_traversal(node.left)
print(node.data)
if node.right:
self.in_order_traversal(node.right)
def rotate_right(self, node):
temp_left_node = node.left_node
t = temp_left_node.right_node
node.left_node = t
temp_left_node.right_node = node
if t is not None:
t.parent = node
temp_parent = node.parent
node.parent = temp_left_node
temp_left_node.parent = temp_parent
if temp_left_node.parent is not None and temp_left_node.parent.left_node == node:
temp_left_node.parent.left_node = temp_left_node
if temp_left_node.parent is not None and temp_left_node.parent.right_node == node:
temp_left_node.parent.right_node = temp_left_node
if node == self.root:
self.root = temp_left_node
def rotate_left(self, node):
temp_right_node = node.right_node
t = temp_right_node.left_node
node.right_node = t
temp_right_node.left_node = node
if t is not None:
t.parent = node
temp_parent = node.parent
node.parent = temp_right_node
temp_right_node.parent = temp_parent
if temp_right_node.parent is not None and temp_right_node.parent.left_node == node:
temp_right_node.parent.left_node = temp_right_node
if temp_right_node.parent is not None and temp_right_node.parent.right_node == node:
temp_right_node.parent.right_node = temp_right_node
if node == self.root:
self.root = temp_right_node
def settle_violation(self,node):
pass
def is_red(self, node):
if node is None:
return False
else:
return node.color == Color.RED