Example 2 : Pair with given sum in a BST

TopicDifficultyCompanies
Binary Search Tree
MEDIUM
Amazon

Given a Binary Search Tree and a target number target. Write a program to check if there exist two elements in the BST such that their sum is equal to the given target.

Problem Note

  • If the two elements exist in BST with the target sum, return 1, else return 0.

Example 1

Input: Below is the given BST.
30
/ \
15 60
/ \ / \
7 22 45 75
/ \
17 27

target = 49
Output: 1
Explanation: The sum of the elements 22 and 27 is equal to 49.

Example 2

Input: Below is the given BST.
30
/ \
15 60
/ \ / \
7 22 45 75
/ \
17 27

target = 5
Output: 0
Explanation: There is no two elements whose sum is equal to 5.

Code Editor

Practice and Learn

Best way to learn is through solving real problems. Practice this problem in this code editor.