解题思路:
按照递归的思想即可解决本题。
1.当root为p,q或者为null的时候返回本身;
2.递归查找其左右子树;
3.根据左右子树的结果,找到规则即可。
具体代码如下:
# 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)
#four cases
if not left and not right:
return None
elif left and not right:
return left
elif not left and right:
return right
return root