Space
Open
From Fieldwork
Scales
Archive
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# Base Case:
# 1. If the tree is empty, return None.
# 2. If we found either p or q, return that node.
if not root or root == p or root == q:
return root
# Recursive Step: Look for p and q in the left and right subtrees
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# Logic:
# If both left and right returned a node, it means p is in one side
# and q is in the other. Therefore, the current 'root' is the split point (LCA).
if left and right:
return root
# If only one side returned a node, it means both p and q are in that specific subtree
# (or one is inside the other). Return the non-None side.
return left or rightPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode