Find a pair with given target in BST
Submissions: 15081   Accuracy:

47.17%

  Difficulty: Medium   Marks: 4

Given a Binary Search Tree and a target sum. Check whether there's a pair of Nodes in the BST with value summing up to the target sum. 

Input:
The first line of input contains the number of test cases T. For each test case, there will be two lines. The first line of each test case is a string representing the tree as described below: 

  1. The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character “N” denotes NULL child.

  2. For example:
     
    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7
    The second line is a target value

Output:
Print 1 if the target sum pair is found else print 0.

Your Task:
You don't need to read input or print anything. Your task is to complete the function
 isPairPresent() that takes a root node and a target value as a parameter and returns True if there's a pair of Nodes in the BST with values summing up to the target sum, else returns False. 

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).

Constraints:
1<=T<=10
1<=Number of Nodes<=100000
1<=K<=1000005

Example:
Input:

2
2 1 3
5
6 5 N 3 N 1 4
2
Output:
1
0

Note: The Input/Output format and Example are given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Saksham Raj Seth
Author: saksham seth


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.