LCA in BST

Binary Search Trees Medium Medium

Given the root node of a binary search tree (BST) and two node values p,q.

Return the lowest common ancestors(LCA) of the two nodes in BST.

Examples:

Input : root = [5, 3, 6, 2, 4, null, 7] , p = 2, q = 4

Output : [3]

Explanation : Below is image of the BST

Input : root = [5, 3, 6, 2, 4, null, 7] , p = 2, q = 7

Output : [5]

Explanation : Below is image of the BST

Input : root = [5, 1, 4, null, null, 3, 6] , p = 1, q = 6

Constraints

  • 1 <= Number of Nodes <= 104
  • 1 <= Node.val <= 105
  • All values in BST are unique.
  • The values p and q are always present in the given BST.

Hints

  • "If both p and q are smaller than root.val, LCA must be in the left subtree: LCA(root,p,q)=LCA(root.left,p,q)if p.val,q.val<root.val If both p and q are greater, LCA is in the right subtree: LCA(root,p,q)=LCA(root.right,p,q)if p.val,q.val>root.val Otherwise, root is the split point, meaning root is the LCA."
  • "By Iterative Approach (Optimized for Space) Start at the root and traverse down the BST until you find the split point. The first node where p and q are on different sides is the LCA."

Company Tags

Rakuten Epic Games AMD Pinterest Western Digital Uber Walmart Electronic Arts HashiCorp HCL Technologies Unity Technologies Visa Twilio KPMG Bloomberg PayPal Swiggy Wayfair Rockstar Games Roblox Robinhood McKinsey & Company Databricks eBay American Express Google Microsoft Amazon Meta Apple Netflix Adobe