-
Notifications
You must be signed in to change notification settings - Fork 26
/
653.TwoSumIV-InputisaBST.py
56 lines (48 loc) · 1.4 KB
/
653.TwoSumIV-InputisaBST.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
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.
Example:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
"""
#Difficulty: Easy
#421 / 421 test cases passed.
#Runtime: 1212 ms
#Memory Usage: 16 MB
#Runtime: 1212 ms, faster than 5.17% of Python3 online submissions for Two Sum IV - Input is a BST.
#Memory Usage: 16 MB, less than 58.51% of Python3 online submissions for Two Sum IV - Input is a BST.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
result = [False]
numbers = []
self.preorder(root, k, result, numbers)
return max(result)
def preorder(self, root, k, result, numbers):
if not root:
return 0
if k - root.val in numbers:
result.append(True)
numbers.append(root.val)
self.preorder(root.left, k, result, numbers)
self.preorder(root.right, k, result, numbers)