File tree Expand file tree Collapse file tree
datastructures/trees/binary Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -45,6 +45,21 @@ def lowest_common_ancestor(
4545def 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 :
You can’t perform that action at this time.
0 commit comments