653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

题目描述

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

1
2
3
4
5
6
7
8
9
10
11
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
1
2
3
4
5
6
7
8
9
10
11
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False

Seen this question in a real interview before? YesNo

题目大意

在搜索二叉树内找到两个数和为target

解题思路

1、通过遍历二叉树,将二叉树转换为字典
2、遍历字典,寻找是否有两个数和为target

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 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
* }
* }
*/
class Solution {
func findTarget(_ root: TreeNode?, _ k: Int) -> Bool {
var dict = [Int: Int]()
func find(tree: TreeNode?) {
guard let t = tree else { return }
dict[t.val] = (dict[t.val] ?? 0) + 1
find(tree: tree?.left)
find(tree: tree?.right)
}
find(tree: root)
for (key, _) in dict {
if key == k - key {
if (dict[k - key] ?? 0) >= 2 {
return true
}
}else if dict[k - key] != nil {
return true
}
}
return false
}
}
0%