美文网首页Leetcode
Leetcode 235. Lowest Common Ance

Leetcode 235. Lowest Common Ance

作者: SnailTyan | 来源:发表于2021-03-26 16:46 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Lowest Common Ancestor of a Binary Search Tree

2. Solution

  • Version 1
# 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, p, q):
        if p.val > q.val:
            p, q = q, p

        if root.val >= p.val and root.val <= q.val:
            return root

        if root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)

        if root.val < p.val:
            return self.lowestCommonAncestor(root.right, p, q)

Reference

  1. https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

相关文章

网友评论

    本文标题:Leetcode 235. Lowest Common Ance

    本文链接:https://www.haomeiwen.com/subject/lttshltx.html