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
相关推荐
Yzzz-F10 小时前
Problem - 2146D1 - Codeforces &&Problem - D2 - Codeforces
算法
Kk.080210 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
环黄金线HHJX.10 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互
Omics Pro10 小时前
虚拟细胞:开启HIV/AIDS治疗新纪元的关键?
大数据·数据库·人工智能·深度学习·算法·机器学习·计算机视觉
书到用时方恨少!10 小时前
Python Pandas 使用指南:数据分析的瑞士军刀
python·数据分析·pandas
旖-旎10 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择
_日拱一卒10 小时前
LeetCode:合并区间
算法·leetcode·职场和发展
汀、人工智能10 小时前
[特殊字符] 第3课:最长连续序列
数据结构·算法·数据库架构·图论·bfs·最长连续序列
少许极端11 小时前
算法奇妙屋(四十一)-贪心算法学习之路 8
学习·算法·贪心算法
Kethy__11 小时前
计算机中级-数据库系统工程师-数据结构-图
数据结构·算法·软考··数据库系统工程师·计算机中级