python--lintcode88. 最近公共祖先

注意事项

  4
/ \
3   7
/ \
5   6


LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

LCA（最近公共父节点）问题是二叉树里很经典的问题了，若是树的结构中有parent指针的话那这一题就很容易了，若没有的话就需要想一想了。

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 is not None and right is not None):
return root      #若左子树找到了A，右子树找到了B，说明此时的root就是公共祖先
if(left is None):    #若左子树是none右子树不是，说明右子树找到了A或B
return right
if(right is None):   #同理
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)

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120