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
    }
相关推荐
他们都不看好你,偏偏你最不争气8 小时前
iOS —— 天气预报仿写总结
ios
白玉cfc15 小时前
【iOS】网易云仿写
ui·ios·objective-c
归辞...17 小时前
「iOS」——内存五大分区
macos·ios·cocoa
HX43618 小时前
MP - List (not just list)
android·ios·全栈
忆江南1 天前
NSProxy是啥,用来干嘛的
ios
忆江南1 天前
dyld
ios
剪一朵云爱着1 天前
力扣二叉树的前序中序后序遍历总结
算法·leetcode·二叉树
归辞...1 天前
「iOS」——GCD其他方法详解
macos·ios·cocoa
游戏开发爱好者82 天前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
Digitally2 天前
如何将 iPhone 备份到 Mac/MacBook
macos·ios·iphone