#235
Lowest Common Ancestor of a Binary Search Tree
medium· Treesruns: 0Given a binary search tree, find the lowest common ancestor (LCA) of two given nodes p and q in the BST. The LCA is the lowest node in the tree that has both p and q as descendants, where a node can be a descendant of itself.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 403
class Solution:
def lowestCommonAncestor(
self, root: TreeNode, p: TreeNode, q: TreeNode
) -> TreeNode:
curr = root
while curr:
if p.val < curr.val and q.val < curr.val:
curr = curr.left
elif p.val > curr.val and q.val > curr.val:
curr = curr.right
else:
return curr
return root
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.