@@ -171,7 +171,7 @@ def __str__(self):
171171 to_be_printed [i ].append (j )
172172 return str (to_be_printed )
173173
174- class ParentPointerTree (object ):
174+ class ParentPointerTree (MAryTree ):
175175 """
176176 Implements a tree with parent pointers.
177177
@@ -296,25 +296,76 @@ def search(self, key, **kwargs):
296296 key
297297 The key for searching.
298298 parent: bool
299- If true then returns index of the
299+ If true then returns node of the
300300 parent of the node with the passed
301301 key.
302302 By default, False
303303
304304 Returns
305305 =======
306306
307- int
308- If the node with the passed key is
307+ ParentPointerTreeNode
308+ The tree node if it was found
309309 in the tree.
310- tuple
311- The index of the searched node and
312- the index of the parent of that node.
313310 None
314311 In all other cases.
315312 """
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
316323
317324
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+
318369 def __str__ (self ):
319370 to_be_printed = ['' for i in range (self .tree ._last_pos_filled + 1 )]
320371 for i in range (self .tree ._last_pos_filled + 1 ):
0 commit comments