二叉树的最近公共祖先二叉搜索树的最近公共祖先
1 二叉树的最近公共祖先
学习:
代码
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None or root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left and right:
return root
if left:
return left
return right
2 二叉搜索树的最近公共祖先
学习
代码
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
x = root.val
if p.val < x and q.val < x: # p 和 q 都在左子树
return self.lowestCommonAncestor(root.left, p, q)
if p.val > x and q.val > x: # p 和 q 都在右子树
return self.lowestCommonAncestor(root.right, p, q)
return root # 其它
学习参考
作者:灵茶山艾府
链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/solutions/2023873/zui-jin-gong-gong-zu-xian-yi-ge-shi-pin-8h2zc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。