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
相关推荐
渔阳节度使13 分钟前
SpringAI实时监控+观测性
后端·python·flask
铁手飞鹰16 分钟前
Visual Studio创建Cmake工程导出DLL,通过Python调用DLL
android·python·visual studio
飞Link26 分钟前
告别盲目找Bug:深度解析 TSTD 异常检测中的预测模型(Python 实战版)
开发语言·python·算法·bug
7yewh40 分钟前
jetson_yolo_deployment 02_linux_dev_skills
linux·python·嵌入式硬件·yolo·嵌入式
记忆多1 小时前
c++名字空间 函数模版 左右值
开发语言·c++·算法
三伏5221 小时前
控制理论前置知识——相平面数学基础2(示例部分)
算法·平面·控制
love530love2 小时前
ComfyUI rgthree-comfy Image Comparer 节点无输出问题排查与解决
人工智能·windows·python·comfyui·rgthree-comfy·nodes 2.0·vue 节点
2401_889884662 小时前
高性能计算通信库
开发语言·c++·算法
badhope2 小时前
Docker从零开始安装配置全攻略
运维·人工智能·vscode·python·docker·容器·github
不想看见4042 小时前
Hamming Distance位运算基础问题--力扣101算法题解笔记
算法