Leetcode刷题--236最近公共祖先

# 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:
            return root
        if root.val == p.val or root.val == q.val:
            return root
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
        if l and r:
            return root
        if l:
            return l
        if r:
            return r

首先确定使用递归的思想先写出

 l = self.lowestCommonAncestor(root.left, p, q)
 r = self.lowestCommonAncestor(root.right, p, q)

然后在考虑返回值如果pq在root的左右两边,那么最近公共祖先肯定是root

如果都在左边,那么公共祖先就是l

如果都在右边,那么公共祖先就是r

        if l and r:
            return root
        if l:
            return l
        if r:
            return r

最后确定迭代的终止条件

 

你可能感兴趣的:(算法)