235. 二叉搜索树的最近公共祖先
题目描述
解题思路
1、二叉树搜索树性质,左子树值均小于父节点值,右子树值均大于父节点值
2、其他参考官方方法二
代码实现
# 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: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return root
while True:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return root
res = root
while True:
if p.val < res.val and q.val < res.val:
res = res.left
elif p.val > res.val and q.val > res.val:
res = res.right
else:
break
return res
参考文献
1、官方题解