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
    }
相关推荐
追夢秋陽12 分钟前
Cocoa 使用NSCollectionView显示列表,数据不足布局异常处理
macos·objective-c·cocoa·swift·collectionview
@大迁世界4 小时前
iOS 26.4 Beta 1 发布日期敲定:苹果开发者预览版何时杀到?
ios
vx-bot5556664 小时前
企业微信ipad协议的多媒体消息处理与文件传输机制
ios·企业微信·ipad
colicode5 小时前
Objective-C语音验证码接口API示例代码:老版iOS应用接入语音验证教程
前端·c++·ios·前端框架·objective-c
2501_916007475 小时前
ios上架 App 流程,证书生成、从描述文件创建、打包、安装验证到上传
android·ios·小程序·https·uni-app·iphone·webview
新缸中之脑6 小时前
SaaS 大灭绝
开发语言·ios·swift
Swift社区6 小时前
LeetCode 389 找不同 - Swift 题解
算法·leetcode·swift
二流小码农1 天前
2026年,在鸿蒙生态里,继续深耕自己
android·ios·harmonyos
2501_915106321 天前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview