-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0653twoSumIV.py
73 lines (59 loc) · 1.65 KB
/
0653twoSumIV.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
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.
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9 Output: True
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28 Output: False
Idea:
1. Since the input is BST, similar to sorted array, when we use binary search. nlogn
2. transfer tree to hash table
either case, binary search and traversal needs to be done. logn
corner case:
1. empty tree
"""
from helper import *
# # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorder(self, tree, target):
if tree is None:
return False
if self.searchBST(self.root, tree, target):
return True
if self.preorder(tree.left, target) or self.preorder(tree.right, target):
return True
return False
def searchBST(self, root, node, target):
if root is None:
return False
else:
if root.val == target - node.val: # assume no duplicates
return not (root is node)
else:
return self.searchBST(root.left if root.val > target - node.val else root.right, node, target)
def findTarget(self, root: TreeNode, k: int) -> bool:
self.root = root
return self.preorder(root, k)
if __name__ == '__main__':
sl = Solution()
nums = "[5, 3, 6, 2, 4, null, 7]"
target = 4
root = stringToTreeNode(nums)
tmp = sl.findTarget(root, target)
print(tmp)