Skip to content

Instantly share code, notes, and snippets.

@iamprayush
Created September 19, 2020 14:16
Show Gist options
  • Save iamprayush/3fbcda22db10be369321964c68d20678 to your computer and use it in GitHub Desktop.
Save iamprayush/3fbcda22db10be369321964c68d20678 to your computer and use it in GitHub Desktop.
Find a pair with a given sum in BST
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
arr, stack = [], []
curr_node = root
while curr_node or stack:
if curr_node:
stack.append(curr_node)
curr_node = curr_node.left
else:
curr_node = stack.pop()
arr.append(curr_node.val)
curr_node = curr_node.right
i, j = 0, len(arr) - 1
while i < j:
curr_sum = arr[i] + arr[j]
if curr_sum == k:
return True
if curr_sum < k:
i += 1
else:
j -= 1
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment