本文转自:https://blog.csdn.net/wenqiwenqi123/article/details/79952043
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
注意事项
假设给出的两个节点都在树中存在
LCA(最近公共父节点)问题是二叉树里很经典的问题了,若是树的结构中有parent指针的话那这一题就很容易了,若没有的话就需要想一想了。
依然用到了分治法的思想,想一想,若是对于一个树结点,在左子树中找到了A,在右子树中找到了B,那说明此结点是公共节点
详细思想写在代码注释里了(对于源代码,本文的代码稍微有点修改)
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowestCommonAncestor(self, root, A, B):
# A&B=>LCA
# !A&!B=>None
# A&!B=>A
# B&!A=>B
if(root is None or root==A or root==B):
return root #若root为空或者root为A或者root为B,说明找到了A和B其中一个
left=self.lowestCommonAncestor(root.left,A,B)
right=self.lowestCommonAncestor(root.right,A,B)
if left and right :
return root #若左子树找到了A,右子树找到了B,说明此时的root就是公共祖先
if not left : #若左子树是none右子树不是,说明右子树找到了A或B
return right
if not right : #同理
return left
return None
a=Tree = TreeNode(2)
b=Tree.left = TreeNode(1)
c=Tree.right = TreeNode(3)
d=b.left=TreeNode(4)
s = Solution()
print(s.lowestCommonAncestor(a,b,d).val)