Problem Solving
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
leeyngdo
2023. 7. 18. 02:52
Problem Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
Lowest Common Ancestor of a Binary Search Tree - LeetCode
Can you solve this real interview question? Lowest Common Ancestor of a Binary Search Tree - 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 [https:
leetcode.com
Solution 1. DFS
Time: $O(\text{log } N)$
Space: $O(1)$

from collections import deque
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def dfs(node):
if node.val <= max(p.val, q.val) and node.val >= min(p.val, q.val):
return node
else:
if node.val > max(p.val, q.val):
return dfs(node.left)
else:
return dfs(node.right)
return dfs(root)