小工具知识网

当前位置: 首页 > 行业知识 > 236. 二叉树的最近公共祖先 (Swift版本)

行业知识

236. 二叉树的最近公共祖先 (Swift版本)

2026-11-12 18:01:26 来源:互联网转载

题目

index.php/tags-41973.html" >���定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

()

数据结构

/** * 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 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 } ()

上一篇:Ruby源码使用详解,轻松掌握Ruby文件夹操作指南

下一篇:【工具】IDEA开发常用配置-编码设置、自动导包、类注释、方法注释、提示自动忽略大小写、自动换行、SQL格式、格式配置等