给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
/**
* 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
* }
* }
*/
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
}