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
    }
相关推荐
Digitally21 分钟前
如何将文件从 iPhone 传输到 Android(新指南)
android·ios·iphone
YungFan1 小时前
iOS26适配指南之通知
ios·swift
木叶丸2 小时前
跨平台方案该如何选择?
android·前端·ios
我唔知啊3 小时前
OC底层原理二:OC对象的分类(实例对象、类对象、元类对象)
ios·objective-c
泓博4 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin
Digitally4 小时前
如何将信息从 iPhone 同步到Mac(完整步骤和示意图)
macos·ios·iphone
大猫会长4 小时前
使用Mac自带的图像捕捉导出 iPhone 相册
ios·iphone
大熊猫侯佩10 天前
消失的它:摆脱 SwiftUI 中“嵌入视图数量不能超过 10 个”限制的秘密
swiftui·swift·apple
大熊猫侯佩10 天前
Swift 抛砖引玉:从数组访问越界想到的“可抛出错误”属性
swift·apple
大熊猫侯佩10 天前
ruby、Python 以及 Swift 语言关于 “Finally” 实现的趣谈
python·ruby·swift