题目描述
见原网址:
235. 二叉搜索树的最近公共祖先
236. 二叉树的最近公共祖先
分析
LCA(Lowest Common Ancestors)问题,即最近公共祖先。
235
根据二分搜索树的性质,某个节点的左子树所有的值均小于该节点的值,而右子树所有节点的值均大于该节点的值,所以有三种情况:
- p、q 的值均小于节点的值,则在节点左子树中寻找公共祖先
- p、q 的值均大于节点的值,则在节点右子树中寻找公共祖先
- p、q 中的一个大于或等于root,另一个小于或等于root,此时 root 都为其公共祖先
236
递归, 对以root为根的(子)树进行查找p和q, 如果root == None or root == p or root == q 直接返回root,此时表示对当前树的查找完毕, 否则对左右子树进行查找, 根据左右子树的返回值判断,分为三种情况:
- 左右子树的返回值都不为None, 由于值唯一左右子树的返回值就是p和q, 此时root为LCA
- 如果左右子树返回值其中一个不为None, 说明p和q同时存在左或右子树中, 最先找到的那个节点为LCA
- 左右子树返回值均为None, p和q均不在树中, 返回None
代码
235
- 递归
# 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 root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
- 迭代
# 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':
while True:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root
236
# 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 or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
elif not left:
return right
elif not right:
return left
更多题目包括leetcode、牛客网、各种排序算法解法参见个人GitHub,持续更新中,欢迎star ~~
https://github.com/PemLer/Journey_of_leetcode