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
    }
相关推荐
AGoodrMe8 小时前
swift基础之async/await
前端·ios
hhb_6188 小时前
Swift核心技术难点与实战案例解析
开发语言·ios·swift
bukeyiwanshui8 小时前
20260518 Swift实验
git·swift
人月神话-Lee9 小时前
【图像处理】饱和度——颜色的浓淡与灰度化
图像处理·人工智能·ios·ai编程·swift
潮起鲸落入海11 小时前
OpenStack块存储管理-cinder对象存储-swift
openstack·swift
青山师11 小时前
二叉树与BST深度解析:遍历算法与平衡策略
数据结构·算法·面试·二叉树·算法与数据结构·java面试·数据结构与算法分析
人月神话-Lee12 小时前
【图像处理】卷积原理与卷积核——图像处理的核心引擎
图像处理·深度学习·ios·ai编程·swift
2501_9151063214 小时前
深入解析无源码iOS加固原理与方案,保护应用安全
android·安全·ios·小程序·uni-app·cocoa·iphone
Daniel_Coder15 小时前
iOS Widget 开发-15:Widget 性能优化指南
ios·swift·widget·widgetcenter
sakiko_16 小时前
Swift学习笔记30-数据库SQlite语句
数据库·学习·swift