前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

作者头像
Tyan
发布2021-04-19 16:19:08
2670
发布2021-04-19 16:19:08
举报
文章被收录于专栏:SnailTyanSnailTyan

1. Description

Lowest Common Ancestor of a Binary Search Tree
Lowest Common Ancestor of a Binary Search Tree

2. Solution

  • Version 1
代码语言:javascript
复制
# 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/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-03-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档