Skip to content

Latest commit

 

History

History
47 lines (36 loc) · 1.28 KB

_235. Lowest Common Ancestor of a Binary Search Tree.md

File metadata and controls

47 lines (36 loc) · 1.28 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 04, 2024

Last updated : July 04, 2024


Related Topics : Tree, Depth-First Search, Binary Search Tree, Binary Tree

Acceptance Rate : 67.82 %


Solutions

Python

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

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        while root :
            if (root == p) or (root == q) :
                break
            if (root.val < p.val) == (root.val > q.val) :
                break
            if root.val < p.val :
                root = root.right
            else :
                root = root.left
        return root