题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
代码
# 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 == q or root == p : return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
return root if left and right else left or right
解题思路
当前root,查看左右子树p,q是否各分布一个,若是,则返回root,不是不断的递归