Advertisement
smj007

LCA of binary tree

Aug 9th, 2024
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | None | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.left = None
  6. #         self.right = None
  7.  
  8. class Solution:
  9.     def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
  10.  
  11.         # This is a weird non-intuitive approach
  12.         # but assume lca function is a proxy for searching any of the nodes in the given tree
  13.         # as soon as you find any of the given node, you return the root of the tree
  14.         # now the catch is if you find a node in the left subtree and right subtree
  15.         # that means the 2 nodes were on the different sides of the subtree so return the root
  16.  
  17.         '''
  18.        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.
  19.        '''
  20.  
  21.         # : 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.
  22.         if not root:
  23.             return None
  24.  
  25.         #  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.
  26.         if root == p or root == q:
  27.             return root
  28.  
  29.         # We recursively search for p and q in the left subtree of the current node. This returns either:
  30.         # 1) the node itself it is p or q
  31.         # 2) the lca found in the left subtree
  32.         # 3) None if neither p or q are found in the left subtree
  33.         left = self.lowestCommonAncestor(root.left, p, q)
  34.         # Similarly we do it for right
  35.         right = self.lowestCommonAncestor(root.right, p, q)
  36.  
  37.         # 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.
  38.         if left and right:
  39.             return root
  40.  
  41.         # 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.
  42.         return left if left else right
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement