-
Notifications
You must be signed in to change notification settings - Fork 17
/
two-sum-iv-input-is-a-bst.py
51 lines (39 loc) · 1.25 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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import Counter
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
if not root:
return False
stack = [root]
last_removed = None
hashmap = Counter()
while stack:
node = stack[-1]
if node.right:
if node.right == last_removed:
hashmap[node.val] += 1
last_removed = stack.pop()
continue
if not node.left or node.left == last_removed:
stack.append(node.right)
continue
if node.left:
if node.left != last_removed:
stack.append(node.left)
continue
hashmap[node.val] += 1
last_removed = stack.pop()
for val, count in hashmap.items():
sub_val = k - val
if sub_val == val:
if hashmap[val] > 1:
return True
else:
if hashmap[sub_val]:
return True
return False