Solving Leetcode Interviews in Seconds with AI: Lowest Common Ancestor of a Binary Search Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "235" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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).” Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. Example 2: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [2,1], p = 2, q = 1 Output: 2 Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the BST.
Explanation
Here's the solution to find the Lowest Common Ancestor (LCA) in a Binary Search Tree (BST), along with an explanation of the approach, complexity analysis, and the Python code.
Key Approach:
- BST Property: Leverage the inherent property of BSTs where all nodes in the left subtree are smaller than the root, and all nodes in the right subtree are larger than the root.
- Iterative Traversal: Iteratively traverse the tree starting from the root.
- LCA Condition: If both
pandqare smaller than the current node, the LCA must be in the left subtree. If both are larger, the LCA must be in the right subtree. If the current node's value falls betweenpandq(or is equal to either), then the current node is the LCA.
Complexity Analysis:
- Runtime Complexity: O(H), where H is the height of the tree. In the worst case (skewed tree), H can be N (number of nodes), leading to O(N). In the best case (balanced tree), H is log(N), leading to O(log(N)).
- Storage Complexity: O(1) - Iterative solution uses constant extra space.
Code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
"""
Finds the lowest common ancestor (LCA) of two nodes in a BST.
"""
current = root
while current:
if p.val < current.val and q.val < current.val:
current = current.left
elif p.val > current.val and q.val > current.val:
current = current.right
else:
return current