235. Lowest Common Ancestor of a Binary Search Tree

2021. 11. 17. 11:41Leetcode

Description:

Given a binary search tree (BST), find the lowest common ancestor (LCA) 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).”

 

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
'''
[1] decision tree)

code::
(below)

-T/C: O(logn)
-S/C: O(h)
'''
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if (root.val>=p.val and root.val<=q.val) or (root.val<=p.val and root.val>=q.val) :
            return root
        
        elif root.val>p.val and root.val>q.val:
            return self.lowestCommonAncestor(root.left,p,q)
        
        elif root.val<p.val and root.val<q.val:
            return self.lowestCommonAncestor(root.right,p,q)

'Leetcode' 카테고리의 다른 글

540. Single Element in a Sorted Array  (0) 2021.11.20
208. Implement Trie (Prefix Tree)  (0) 2021.11.17
62. Unique Paths  (0) 2021.11.17
230. Kth Smallest Element in a BST  (0) 2021.11.16
98. Validate Binary Search Tree  (0) 2021.11.16