专栏首页SnailTyanLeetcode 235. Lowest Common Ancestor of a Binary Search Tree

Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

1. Description

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/

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two ...

    triplebee
  • LeetCode 235 Lowest Common Ancestor of a Binary Search Tree

    题解:递归的时候判断如果两个节点的值在父节点两边,那个这个父节点就是最近的公共父节点。否则按照二叉搜索树的规则递归下去。

    ShenduCC
  • 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 公共祖先

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two g...

    韩旭051
  • Tree - 235. Lowest Common Ancestor of a Binary Search Tree

    235. Lowest Common Ancestor of a Binary Search Tree

    用户5705150
  • 235. Lowest Common Ancestor of a Binary Search Tree(Tree-Easy)

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two g...

    Jack_Cui
  • Golang Leetcode 235. Lowest Common Ancestor of a Binary Search Tree.go

    版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89043473

    anakinsun
  • Js算法与数据结构拾萃(4):二叉树

    因此只要答对这道题,你就可以超越世界级大牛,问鼎码林之巅(逃) 导读: •二叉树知识重点•二叉树深度不一,因此天生适用递归,因此可用递归处理•判断两树相等•翻转...

    一粒小麦
  • 【LeetCode 236.二叉树的最近公共祖先】双解法:递归实现 + 利用父指针

    这题相较于 LeetCode 235.二叉搜索树的最近公共祖先 的递归思考起来比较有难度。

    心谭博客
  • Tree - 236. Lowest Common Ancestor of a Binary Tree

    236. Lowest Common Ancestor of a Binary Tree

    用户5705150

扫码关注云+社区

领取腾讯云代金券