forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwo-sum-iv-input-is-a-bst.py
45 lines (39 loc) · 1.36 KB
/
two-sum-iv-input-is-a-bst.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
# Time: O(n)
# Space: O(h)
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
class BSTIterator(object):
def __init__(self, root, forward):
self.__node = root
self.__forward = forward
self.__s = []
self.__cur = None
self.next()
def val(self):
return self.__cur
def next(self):
while self.__node or self.__s:
if self.__node:
self.__s.append(self.__node)
self.__node = self.__node.left if self.__forward else self.__node.right
else:
self.__node = self.__s.pop()
self.__cur = self.__node.val
self.__node = self.__node.right if self.__forward else self.__node.left
break
if not root:
return False
left, right = BSTIterator(root, True), BSTIterator(root, False)
while left.val() < right.val():
if left.val() + right.val() == k:
return True
elif left.val() + right.val() < k:
left.next()
else:
right.next()
return False