在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given two binary search trees, return Example 1: Input: root1 = 5
Output: true
Explanation: 2 and 3 sum up to 5.
Example 2: Input: root1 = 18
Output: false
Note:
给出两棵二叉搜索树,请你从两棵树中各找出一个节点,使得这两个节点的值之和等于目标值 如果可以找到返回
示例 1: 输入:root1 = [2,1,4], root2 = [1,0,3], target = 5 输出:true 解释:2 加 3 和为 5 。 示例 2: 输入:root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18 输出:false
提示:
Runtime: 168 ms
Memory Usage: 23 MB
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func twoSumBSTs(_ root1: TreeNode?, _ root2: TreeNode?, _ target: Int) -> Bool { 16 var s1:Set<Int> = Set<Int>() 17 var s2:Set<Int> = Set<Int>() 18 get(&s1, root1) 19 get(&s2, root2) 20 for i in s1 21 { 22 if s2.contains(target-i) {return true} 23 } 24 return false 25 } 26 27 func get(_ s:inout Set<Int>,_ root: TreeNode?) 28 { 29 if root != nil 30 { 31 s.insert(root!.val) 32 get(&s, root!.left) 33 get(&s, root!.right) 34 } 35 } 36 }
|
请发表评论