Skip to content

Commit c928032

Browse files
committed
feat(datastructures, binary tree): lowest common ancestor
1 parent b133f6d commit c928032

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

datastructures/trees/binary/utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ def lowest_common_ancestor(
4545
def lowest_common_ancestor_ptr(
4646
node_one: BinaryTreeNode, node_two: BinaryTreeNode
4747
) -> BinaryTreeNode | None:
48+
"""
49+
Returns the lowest common ancestor of 2 nodes in the Binary Tree using a two-pointer approach.
50+
51+
This algorithm uses two pointers starting at node_one and node_two. Both pointers move up the tree
52+
via parent pointers. When a pointer reaches the root (parent is None), it switches to the other
53+
starting node. By switching starting points, both pointers travel the same total distance and meet
54+
at the lowest common ancestor.
55+
56+
Time Complexity: O(h) where h is the height of the tree
57+
Space Complexity: O(1) as only two pointers are used
58+
59+
:param node_one: BinaryTreeNode
60+
:param node_two: BinaryTreeNode
61+
:return: BinaryTreeNode | None - The lowest common ancestor, or None if not found
62+
"""
4863
ptr1, ptr2 = node_one, node_two
4964

5065
while ptr1 != ptr2:

0 commit comments

Comments
 (0)