@@ -171,7 +171,7 @@ def __str__(self):
171
171
to_be_printed [i ].append (j )
172
172
return str (to_be_printed )
173
173
174
- class ParentPointerTree (object ):
174
+ class ParentPointerTree (MAryTree ):
175
175
"""
176
176
Implements a tree with parent pointers.
177
177
@@ -296,25 +296,76 @@ def search(self, key, **kwargs):
296
296
key
297
297
The key for searching.
298
298
parent: bool
299
- If true then returns index of the
299
+ If true then returns node of the
300
300
parent of the node with the passed
301
301
key.
302
302
By default, False
303
303
304
304
Returns
305
305
=======
306
306
307
- int
308
- If the node with the passed key is
307
+ ParentPointerTreeNode
308
+ The tree node if it was found
309
309
in the tree.
310
- tuple
311
- The index of the searched node and
312
- the index of the parent of that node.
313
310
None
314
311
In all other cases.
315
312
"""
313
+ parent = kwargs .get ('parent' , False )
314
+
315
+ for idx in range (self .size ):
316
+ node = self .tree [idx ]
317
+ if node is not None and node .key == key :
318
+ if parent :
319
+ return node .parent
320
+ return node
321
+
322
+ return None
316
323
317
324
325
+ def least_common_ancestor (self , first_child_key , second_child_key ):
326
+ """
327
+ Finds the least common ancestor of two nodes in
328
+ the tree.
329
+
330
+ Parameters
331
+ ==========
332
+
333
+ first_child_key
334
+ The key of the first child node.
335
+ second_child_key
336
+ The key of the second child node.
337
+
338
+ Returns
339
+ =======
340
+
341
+ ParentPointerTreeNode
342
+ The least common ancestor node.
343
+ None
344
+ If either of the nodes doesn't exist in the tree.
345
+ """
346
+ first_node_idx = self .search (first_child_key )
347
+ second_node_idx = self .search (second_child_key )
348
+
349
+ # One or both nodes do not exist
350
+ if first_node_idx is None or second_node_idx is None :
351
+ return None
352
+
353
+ first_node = self .tree [first_node_idx ]
354
+ second_node = self .tree [second_node_idx ]
355
+
356
+ first_ancestors = set ()
357
+
358
+ while first_node is not None :
359
+ first_ancestors .add (first_node )
360
+ first_node = first_node .parent
361
+
362
+ while second_node is not None :
363
+ if second_node in first_ancestors :
364
+ return second_node # Found the least common ancestor
365
+ second_node = second_node .parent
366
+
367
+ return None # No common ancestor found
368
+
318
369
def __str__ (self ):
319
370
to_be_printed = ['' for i in range (self .tree ._last_pos_filled + 1 )]
320
371
for i in range (self .tree ._last_pos_filled + 1 ):
0 commit comments