Given the root of a Binary Search Tree (BST) and an integer target, return true
if there exist two elements in the BST such that their sum is equal to the given target, or false
otherwise.
Input: root = [5,3,6,2,4,null,7], target = 9
Output: true
Explanation: 3 + 6 = 9
Input: root = [5,3,6,2,4,null,7], target = 28
Output: false
Explanation: There are no two nodes in the BST that add up to 28.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findTarget(root: TreeNode, target: int) -> bool:
# Helper function for inorder traversal
def inorder(node: TreeNode) -> list:
if not node:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
# Convert BST to a sorted list using inorder traversal
values = inorder(root)
# Use two pointers to find the target sum in the sorted list
left, right = 0, len(values) - 1
while left < right:
current_sum = values[left] + values[right]
if current_sum == target:
return True
elif current_sum < target:
left += 1
else:
right -= 1
return False
Overall time complexity is O(n) where n is the number of nodes in the BST.
Thus, the overall space complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?