Skip to content

Commit

Permalink
Lowest Common Ancestor of a Binary Search Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-sukhoverkhov committed Jun 14, 2024
1 parent 21793ef commit 0031a85
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions python/leetcode/Lowest Common Ancestor of a Binary Search Tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from python.leetcode.libs.tree import TreeNode


class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

min_node, max_node = (p, q) if p.val < q.val else (q, p)

answer = None

def traceback(node):
nonlocal answer
if not node:
return

if node.val >= min_node.val and node.val <= max_node.val:
answer = node
return

if node.val < min_node.val and node.val < max_node.val:
traceback(node.right)
else:
traceback(node.left)

traceback(root)

return answer


if __name__ == "__main__":
obj = Solution()

root = TreeNode.array_to_tree([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])
p = 2
q = 4
assert obj.lowestCommonAncestor(root, root.left, root.left.right).val == root.left.val

root = TreeNode.array_to_tree([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])
assert obj.lowestCommonAncestor(root, root.left, root.right).val == root.val

0 comments on commit 0031a85

Please sign in to comment.