Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

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

1. Description

Lowest Common Ancestor of a Binary Search Tree

2. Solution

思路:由于树是有序的,因此先对p, q排序,p小于q,因此在树中p一定在于最低祖先结点的左子树(包含当前结点),q位于右子树(包含当前结点),比较p, q结点与当前结点的值,找到这样的结点即为最低最先结点。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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/
如果有收获,可以请我喝杯咖啡!