Created
September 19, 2020 14:16
-
-
Save iamprayush/3fbcda22db10be369321964c68d20678 to your computer and use it in GitHub Desktop.
Find a pair with a given sum in BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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