forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
two-sum-iv-input-is-a-bst.py
77 lines (70 loc) · 1.88 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
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
74
75
76
77
# Time: O(n)
# Space: O(h)
# 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 1:
# Input:
# 5
# / \
# 3 6
# / \ \
# 2 4 7
#
# Target = 9
#
# Output: True
# Example 2:
# Input:
# 5
# / \
# 3 6
# / \ \
# 2 4 7
#
# Target = 28
#
# Output: False
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
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