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
    }
相关推荐
Mr.NickJJ41 分钟前
Swift系列02-Swift 数据类型系统与内存模型
开发语言·ios·swift
二流小码农1 小时前
鸿蒙开发:wrapBuilder传递参数
android·ios·harmonyos
火柴就是我3 小时前
flutter rust bridge 编译成so 文件 或者 .a文件 依赖到主项目
flutter·ios·rust
YungFan4 小时前
iOS开发之网络代码进化史
ios·swift
xiao--xin6 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
SunshineBrother10 小时前
shell脚本,怎么查找项目中的重复图片
ios
月未央10 小时前
HarmonyOS Next 开发系列:Provider和Consumer状态修饰器实践
ios·harmonyos
北京自在科技1 天前
【Find My功能科普】防盗黑科技如何改变生活?
科技·ios·生活·findmy
橘子真甜~1 天前
32.C++二叉树进阶1(二叉搜索树)
开发语言·数据结构·c++·面试·二叉树·二叉搜索树
水木姚姚2 天前
图形界面控件编程(iOS)
人工智能·python·macos·ios·xcode