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
    }
相关推荐
健了个平_241 小时前
LottieConverter:一键生成 .lottie 文件
ios·chatgpt·动效
开心就好20254 小时前
Win11 抓包工具怎么选?网页请求与设备流量抓取
后端·ios
恋猫de小郭6 小时前
你的蓝牙设备可能正在泄漏你的隐私? Bluehood 如何追踪附近设备并做隐私分析
android·前端·ios
UXbot10 小时前
AI App 设计生成工具哪个好?
ui·kotlin·软件构建·产品经理·ai编程·swift
FreeBuf_12 小时前
Coruna漏洞利用工具揭示Triangulation iOS攻击框架的演进
macos·ios·cocoa
2501_9159184112 小时前
WebKit 抓包,WKWebView 请求的完整数据获取方法
android·前端·ios·小程序·uni-app·iphone·webkit
黄林晴13 小时前
Swift 杀进 Android,Google 和 Apple 都要失眠了?
android·前端·swift
东坡肘子13 小时前
一墙之隔,不同的时空 -- 肘子的 Swift 周报 #129
人工智能·swiftui·swift
ssshooter1 天前
Tauri 2 iOS 开发避坑指南:文件保存、Dialog 和 Documents 目录的那些坑
前端·后端·ios