/daily leetcode 2

permalink: /archive/posts/daily_leetcode_2/
date: Wed Sep 21 2022 00:00:00 GMT+0000 (Coordinated Universal Time)

392. Lowest Common Ancestor of a Binary Search Tree


Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Despite this one being listed as medium, it was pretty simple for me considering the absurd amount of BST traversals I did in college. A basic recursion is all that is needed.

In a BST, a root's left children are always smaller than itself and it's right children are always larger. Because of this basic property, you can infer an LCA pretty easily by understanding that if any two nodes have a value less than the root node, the ancestor must be a left child of the root, and vice versa. If you find that p and q are not both smaller or both larger than the current (root) node, then the current node must be the LCA. This is also possible even when p or q is the root node because a node can be a descendant of itself.

# 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':
if not root:
return null

if (p.val < root.val and q.val < root.val):
return self.lowestCommonAncestor(root.left, p, q)

if (p.val > root.val and q.val > root.val):
return self.lowestCommonAncestor(root.right, p, q)

return root