File tree Expand file tree Collapse file tree
exercises/1000_programs/medium Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Node :
2+ def __init__ (self , val ):
3+ self .val = val
4+ self .left = None
5+ self .right = None
6+ self .parent = None
7+
8+ def lowest_common_ancestor (p : 'Node' , q : 'Node' ) -> 'Node' :
9+ """
10+ Find the lowest common ancestor of two nodes in a binary tree
11+ where each node has a pointer to its parent.
12+ """
13+ if not p or not q :
14+ return None
15+
16+ a , b = p , q
17+
18+ # This approach mimics finding the intersection of two linked lists.
19+ # By switching paths, both pointers travel the same total distance:
20+ # (distance p to LCA + distance q to LCA + distance LCA to root)
21+ while a != b :
22+ a = a .parent if a .parent else q
23+ b = b .parent if b .parent else p
24+
25+ return a
26+
27+ if __name__ == "__main__" :
28+ # Example Setup:
29+ # 3
30+ # / \
31+ # 5 1
32+ # / \
33+ # 6 2
34+
35+ root = Node (3 )
36+ node5 = Node (5 )
37+ node1 = Node (1 )
38+ node6 = Node (6 )
39+ node2 = Node (2 )
40+
41+ root .left , root .right = node5 , node1
42+ node5 .parent , node1 .parent = root , root
43+
44+ node5 .left , node5 .right = node6 , node2
45+ node6 .parent , node2 .parent = node5 , node5
46+
47+ # Test Case: LCA of 6 and 2 should be 5
48+ result = lowest_common_ancestor (node6 , node2 )
49+
50+ print (f"Input Nodes: { node6 .val } , { node2 .val } " )
51+ print (f"LCA Output: { result .val if result else 'None' } " )
You can’t perform that action at this time.
0 commit comments