본문 바로가기
Problem Solving

[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree

by leeyngdo 2023. 7. 18.

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)

 

'Problem Solving' 카테고리의 다른 글

[Leetcode] 733. Flood Fill  (0) 2023.07.18
[Leetcode] 704. Binary Search  (0) 2023.07.17
[Leetcode] 242. Valid Anagram  (0) 2023.07.13
[Leetcode] 226. Invert Binary Tree  (0) 2023.07.13
[Leetcode] 125. Valid Palindrome  (0) 2023.07.12