653. Two Sum IV - Input is a BST
Easy
Input: root = [5,3,6,2,4,null,7], k = 9
Output:
trueInput: root = [5,3,6,2,4,null,7], k = 28
Output:
falseLast updated
Input: root = [5,3,6,2,4,null,7], k = 9
Output:
trueInput: root = [5,3,6,2,4,null,7], k = 28
Output:
falseLast updated
class Solution:
def findTarget(self, root: Optional[TreeNode], target: int) -> bool:
d = defaultdict(int)
def traverse(root):
if not root:
return False
remain = target - root.val
if remain in d and d[remain] > 0:
return True
d[root.val] += 1
return traverse(root.left) or traverse(root.right)
return traverse(root)