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
    }
相关推荐
SY.ZHOU1 天前
大型工程跨全平台实践总结
flutter·ios·安卓·鸿蒙
denggun123451 天前
Sendable 协议-Swift 结构化并发的核心安全保障
ios·swift
奶糖的次元空间1 天前
iOS 学习笔记 - 创建第一个APP
ios
for_ever_love__1 天前
Objective-C 学习 NSString 和 NSMutableString的基本功能详解
学习·ios·objective-c
@大迁世界1 天前
注意,苹果刚刚做出改变: iOS 26.4 系统强制所有设备开启“被盗设备保护”功能。
macos·ios·objective-c·cocoa
卢锡荣2 天前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑
2501_907136822 天前
iOS任意版本号APP下载
ios·软件需求
denggun123452 天前
结构化并发(Structured Concurrency)
开发语言·ios·swift
Yvonne爱编码2 天前
二叉树高频题精讲 | 从入门到熟练掌握二叉树操作
java·开发语言·数据结构·链表·二叉树
weixin_403810132 天前
EasyClick iOS USB版本蓝牙点击坐标代码
ios·自动化·代理模式