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
相关推荐
不想看见4041 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone1 小时前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球09292 小时前
寒假打卡:2026-2-23
数据结构·算法
Loo国昌2 小时前
【AI应用开发实战】09_Prompt工程与模板管理:构建可演进的LLM交互层
大数据·人工智能·后端·python·自然语言处理·prompt
田里的水稻2 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z2 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
遨游xyz2 小时前
Trie树(字典树)
开发语言·python·mysql
郝学胜-神的一滴2 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~2 小时前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法