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
    }
相关推荐
WDeLiang11 小时前
Flutter 环境搭建
flutter·ios·visual studio code
lilili啊啊啊18 小时前
iOS 应用性能测试工具对比:Xcode Instruments、克魔助手与性能狗
测试工具·ios·iphone·xcode·克魔
264玫瑰资源库1 天前
嘻游电玩三端客户端部署实战:PC + Android + iOS 环境全覆盖教程
android·ios
鸿蒙布道师1 天前
鸿蒙NEXT开发权限工具类(申请授权相关)(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
鸿蒙布道师1 天前
鸿蒙NEXT开发定位工具类 (WGS-84坐标系)(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
好易学数据结构2 天前
可视化图解算法:按之字形顺序打印二叉树( Z字形、锯齿形遍历)
数据结构·算法·leetcode·面试·二叉树·力扣·笔试·遍历·二叉树遍历·牛客网·层序遍历·z·z字形遍历·锯齿形遍历
ghhgy5312 天前
已安装爱思助手和Apple相关驱动,但仍无法有线连接iPhone热点,且网络适配器没有Apple Mobile Device Ethernet,问题解决
ios·iphone
陈皮话梅糖@2 天前
iOS error: some files could not be transferred (code 23) at xxx
ios
林晨月2 天前
SwiftUI Color(一)
ios·swiftui
Andy3222 天前
030 期 3个神器让你的Mac更聪明!
ios·github·mac