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

Example 1:
Input: 5 / \ 3 6 / \ \ 2 4 7

Target = 9

Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7

Target = 28

Output: False

Solution

The problem can be solved with Tree Traversal and maintaining the visited node in HashSet. While traversing a tree we can do lookup in HashSet with value k – node.val, If such value found then we have pair having sum as k.

Code

Output

true

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.

Leave a Reply

Your email address will not be published. Required fields are marked *