Problem
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).”
Logic
To have two queues of the path (traversing based on binary search tree logic) and then traverse both queues, and once you find a discrepancy return previous node. I am aware that you can somehow do it without queues using BST logic, and I will optimize it eventually. But I am just wondering why this is not working.
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
queueForp = collections.deque()
queueForq = collections.deque()
phead = root
qhead = root
while phead != None:
queueForp.append(phead)
if phead == p:
phead = None
else:
if phead.val < p.val:
phead = phead.right
else:
phead = phead.left
while qhead!= None:
queueForq.append(qhead)
if qhead == q:
qhead = None
else:
if qhead.val < q.val:
qhead = qhead.right
if qhead.val > q.val:
qhead = qhead.left
print(queueForp)
print(queueForq)
prev = None
while len(queueForp)!= 0 and len(queueForq) != 0:
currp = queueForp.popleft()
currq = queueForq.popleft()
if currp.val == currq.val:
prev = currp
else:
return prev
return prev
Issue
It fails on a really large input about 10k
p = 5893
q = 3379
Output: 41 Expected: 5734 Alternatively, you could try putting this code in leetcode and get the test case. What am I doing wrong?