236. 二叉树的最近公共祖先 (Swift版本)

题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

数据结构

swift 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */
  • 树中节点数目在范围 [2, 105] 内。
  • -109 <= Node.val <= 109
  • 所有 Node.val 互不相同 。
  • p != q
  • p 和 q 均存在于给定的二叉树中。

Show me the code

swift 复制代码
    func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? {
        var result: TreeNode? = nil
        func containAnyTarget(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> Bool {
            guard root != nil else { return false }
            let lson = containAnyTarget(root!.left, p, q)
            let rson = containAnyTarget(root!.right, p, q)
            if lson == true, rson == true {
                result = root
                return true
            }
            if root === p || root === q { 
                result = root
                return true
            }
            return lson || rson
        }
        let _ = containAnyTarget(root, p, q)
        return result
    }
相关推荐
pop_xiaoli15 分钟前
【iOS】RunLoop
macos·ios·objective-c·cocoa
区块block3 小时前
iOS 27 重磅开放:第三方 AI 模型自由切换,苹果生态告别封闭
人工智能·ios
人月神话Lee6 小时前
【图像处理】亮度与对比度——图像的线性变换
ios·ai编程·图像识别
bryceZh7 小时前
iOS26适配-UISplitViewController配置分栏和分屏
ios·ui kit
songgeb7 小时前
NumberFormatter 货币格式化属性详解
ios·swift
for_ever_love__11 小时前
UI学习:数据驱动ce l l
学习·ui·ios·objective-c
KillerNoBlood11 小时前
2026移动端跨平台开发面经总结
android·算法·flutter·ios·移动开发·鸿蒙·kmp
人月神话-Lee12 小时前
【图像处理】颜色科学与灰度化——人眼看到的和数字记录的不一样
图像处理·人工智能·计算机视觉·ios·swift
号码认证服务12 小时前
给用户打电话,怎么在对方手机显示为“XX证券”?号码认证办理步骤
android·运维·服务器·ios·智能手机·iphone·webview
MonkeyKing12 小时前
iOS 启动优化实战:pre-main耗时、二进制重排与动态库裁剪全解析
ios