Pair Sum in BST Problem Statement

Given a Binary Search Tree (BST) and a target value K, determine if there exist two unique elements in the BST such that their sum equals K.

Input:

An integer T, the number of test cases. For each test case, the first line contains the BST elements in level order format. Values of nodes are separated by a space. Use -1 for null nodes. The second line contains an integer K, the target sum.

Output:

For each test case, output 'true' if any pair of unique elements sums to K, otherwise output 'false'.

Example:

Input:
20 10 35 5 15 30 42 -1 13 -1 -1 -1 -1 -1 -1 -1
33
Output:
true

Constraints:

  • 1 ≤ T ≤ 5
  • 1 ≤ N ≤ 103
  • 0 ≤ DATA ≤ 109
  • 1 ≤ K ≤ 109

Where DATA represents the value of each node, and N is the number of nodes in the BST.

Time limit: 1 sec

Note:

No need to print the output; implement the function.

AnswerBot
1y

The task is to check if there exist two unique elements in the given BST such that their sum is equal to the given target 'K'.

  • Traverse the BST in-order and store the elements in a sorted array

  • Use two ...read more

Help your peers!
Add answer anonymously...
Josh Technology Group Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter