236. 二叉树的最近公共祖先

  1. 题目链接
  2. 解题思路:二叉树递归套路。从左儿子收集信息,从右儿子收集信息,然后得到本节点的信息,再返回给自己的父亲节点。
    • 从儿子收集什么信息?
    • 左儿子是否包含p?左儿子是否包含q?右儿子是否包含p?右儿子是否包含q
    • 任意一个儿子包含p,那么本节点就包含p,任意一个儿子包含q,那么本节点就包含q
    • 如果该节点同时包含p和q那么直接返回结果了(结果放在参数中收集)。
    • 有一种特殊情况,就是该节点就是p或者q
  1. 代码

    class Solution:
        class Info:
            def __init__(self, has_p, has_q):
                self.has_p = has_p    # 子树上是否包含p
                self.has_q = has_q    # 子树上是否包含q
    
        def process(self, head, ans, p, q):
            if ans[0]:
                return None
            if head is None:
                return self.Info(False, False)
            has_p = head == p
            has_q = head == q
    
            # 处理左子树
            left_info = self.process(head.left, ans, p, q)
            if left_info is None:  # 返回None只有一种可能  就是已经找到答案了  就是ans
                return None
            has_p = has_p or left_info.has_p   # 如果左子树上有了  那么以当前节点为头的子树也有了
            has_q = has_q or left_info.has_q
    
            # 处理右子树
            right_info = self.process(head.right, ans, p, q)
            if right_info is None:
                return None
            has_p = has_p or right_info.has_p
            has_q = has_q or right_info.has_q
            if has_p and has_q:
                ans[0] = head
                return None
            return self.Info(has_p, has_q)
    
    
        def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
            ans = [None]
            self.process(root, ans, p, q)
            return ans[0]
    
posted @ 2025-02-13 16:12  ouyangxx  阅读(10)  评论(0)    收藏  举报