题目
思路
1.如果root==A或者root==B,返回root作为LCA
2.找到左子树和右子树是否包含A或者B,如果都包含,返回root,否则返回左子树的LCA或者右子树的LCA
3.都不满足,返回None
代码
"""
Definition of TreeNode:
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):
# write your code here
if not root or root == A or root == B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right: return root
if left: return left
if right: return right
return None