Skip to content

Commit 6897169

Browse files
authored
Added make_root in DSU (#342)
1 parent 83ed2ff commit 6897169

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

pydatastructs/miscellaneous_data_structures/disjoint_set.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ class DisjointSetForest(object):
1616
>>> dst.union(1, 2)
1717
>>> dst.find_root(2).key
1818
1
19+
>>> dst.make_root(2)
20+
>>> dst.find_root(2).key
21+
2
1922
2023
References
2124
==========
@@ -74,3 +77,29 @@ def union(self, key1, key2):
7477

7578
y_root.parent = x_root
7679
x_root.size += y_root.size
80+
81+
def make_root(self, key):
82+
"""
83+
Finds the set to which the key belongs
84+
and makes it as the root of the set.
85+
"""
86+
if self.tree.get(key, None) is None:
87+
raise KeyError("Invalid key, %s"%(key))
88+
89+
key_set = self.tree[key]
90+
if key_set.parent is not key_set:
91+
current_parent = key_set.parent
92+
# Remove this key subtree size from all its ancestors
93+
while current_parent.parent is not current_parent:
94+
current_parent.size -= key_set.size
95+
current_parent = current_parent.parent
96+
97+
all_set_size = current_parent.size # This is the root node
98+
current_parent.size -= key_set.size
99+
100+
# Make parent of current root as key
101+
current_parent.parent = key_set
102+
# size of new root will be same as previous root's size
103+
key_set.size = all_set_size
104+
# Make parent of key as itself
105+
key_set.parent = key_set

pydatastructs/miscellaneous_data_structures/tests/test_disjoint_set.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,44 @@ def test_DisjointSetForest():
2121
assert raises(KeyError, lambda: dst.find_root(9))
2222
dst.union(3, 1)
2323
assert dst.find_root(3).key == 1
24+
assert dst.find_root(5).key == 1
25+
dst.make_root(6)
26+
assert dst.find_root(3).key == 6
27+
assert dst.find_root(5).key == 6
28+
dst.make_root(5)
29+
assert dst.find_root(1).key == 5
30+
assert dst.find_root(5).key == 5
31+
assert raises(KeyError, lambda: dst.make_root(9))
32+
33+
dst = DisjointSetForest()
34+
for i in range(6):
35+
dst.make_set(i)
36+
assert dst.tree[2].size == 1
37+
dst.union(2, 3)
38+
assert dst.tree[2].size == 2
39+
assert dst.tree[3].size == 1
40+
dst.union(1, 4)
41+
dst.union(2, 4)
42+
# current tree
43+
###############
44+
# 2
45+
# / \
46+
# 1 3
47+
# /
48+
# 4
49+
###############
50+
assert dst.tree[2].size == 4
51+
assert dst.tree[1].size == 2
52+
assert dst.tree[3].size == dst.tree[4].size == 1
53+
dst.make_root(4)
54+
# New tree
55+
###############
56+
# 4
57+
# |
58+
# 2
59+
# / \
60+
# 1 3
61+
###############
62+
assert dst.tree[4].size == 4
63+
assert dst.tree[2].size == 3
64+
assert dst.tree[1].size == dst.tree[3].size == 1

0 commit comments

Comments
 (0)