Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Definition for a binary tree node.
- # class TreeNode:
- # def __init__(self, x):
- # self.val = x
- # self.left = None
- # self.right = None
- class Solution:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
- # This is a weird non-intuitive approach
- # but assume lca function is a proxy for searching any of the nodes in the given tree
- # as soon as you find any of the given node, you return the root of the tree
- # now the catch is if you find a node in the left subtree and right subtree
- # that means the 2 nodes were on the different sides of the subtree so return the root
- '''
- To find the LCA, the key insight is to use recursion to traverse the tree, looking for p and q. As we traverse the tree, we check whether the current node is an ancestor of either p or q, and from there, we can determine the lowest common ancestor by combining the results from the left and right subtrees.
- '''
- # : If the current node is None, it means we've reached the end of a branch without finding either p or q. Therefore, we return None.
- if not root:
- return None
- # If the current node is either p or q, we return the current node because one of the nodes we are looking for is found.
- if root == p or root == q:
- return root
- # We recursively search for p and q in the left subtree of the current node. This returns either:
- # 1) the node itself it is p or q
- # 2) the lca found in the left subtree
- # 3) None if neither p or q are found in the left subtree
- left = self.lowestCommonAncestor(root.left, p, q)
- # Similarly we do it for right
- right = self.lowestCommonAncestor(root.right, p, q)
- # If both left and right are not None, it means that p and q are found in different subtrees of the current node. Hence, the current node (root) is their lowest common ancestor.
- if left and right:
- return root
- # If only left is not None, it means both p and q are located in the left subtree, so we return left (which may be the LCA or one of the nodes p or q). Similarly, if only right is not None, we return right.
- return left if left else right
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement