Leetcode 236. Lowest Common Ancestor of a Binary Tree

Problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Algorithm

Recursively solve LCA. Determine if elements are in the left or right subtree. If found in both subtrees, the current node is the LCA.

Code

python3 复制代码
# 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 None
        
        if root == p or root == q:
            return root
        
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        
        if left and right:
            return root
        elif left:
            return left
        else:
            return right
相关推荐
卷无止境5 小时前
FastAPI Users 全面解析:概念、原理与工程实战
后端·python
COOLMO研究AI5 小时前
Python 如何在 AI 接口中实现请求幂等性:防止重复提交与重复扣费
人工智能·python·php
CTA量化套保6 小时前
新手学量化,先做能复查的小流程
人工智能·python
ctlover6 小时前
Python文件操作
开发语言·python
luj_17686 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
AndrewHZ6 小时前
图像处理入门(第005期):颜色空间入门——RGB/HSV/CMYK/Lab
图像处理·python·opencv·hsv·rgb·色彩空间
风流 少年6 小时前
Spring AI 2.0:Tool
java·python·spring
郝学胜-神的一滴7 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程
WangY_ZQ7 小时前
【无标题】
windows·python
桐桐桐7 小时前
PDF 翻译工具横评与自建批量方案:从在线工具到 Python 自动化
python·pdf·自动化