leetcode:二叉搜索树的最近公共祖先

题目描述

解题思路

根据二叉搜索树的特点,当根节点大于等于p或q作为左孩子,且小于等于p或q作为右孩子,满足根节点是最近公共祖先,不满足条件时,递归地进行搜索

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class :
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
parent_val = root.val
p_val = p.val
q_val = q.val
if p_val > parent_val and q_val > parent_val:
return self.lowestCommonAncestor(root.right, p, q)
elif p_val < parent_val and q_val < parent_val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root