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
    }
相关推荐
2601_955767422 天前
圆偏振光AR膜实测:反射率≤0.5%+96%透光率,iPhone17 Pro贴膜久看不累——观复盾上手
人工智能·科技·ios·ar·iphone·圆偏振光
2501_915106322 天前
iOS开发工具有哪些?iOS 开发每个阶段的实用工具
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
Digitally2 天前
如何将数据从 iPhone 传输到传音 Infinix 手机
ios·智能手机·iphone
8Qi82 天前
LeetCode 236. 二叉树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·lca·后序遍历
库奇噜啦呼2 天前
【iOS】源码学习-KVC与KVO
学习·ios·cocoa
黑化旺仔2 天前
iOS - 3G share仿写总结
ios
Digitally2 天前
适用于安卓、iOS 和电脑的最新文件共享应用评测指南
android·ios·电脑
少司府2 天前
C++进阶:二叉搜索树
开发语言·数据结构·c++·二叉树·stl·二叉搜索树·tree
8Qi82 天前
LeetCode 124. 二叉树中的最大路径和(Hard)
算法·leetcode·二叉树·递归