Pair Sum in Binary Search Tree

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 the target 'K'.

Explanation:

A BST is a type of binary tree where each node has a maximum of two children, and it satisfies the following properties:

• The left subtree of a node contains only nodes with values less than the node's value.
• The right subtree of a node contains only nodes with values greater than the node's value.
• Both the left and right subtrees must also be BSTs.

Input:

The first line contains an integer ‘T’, representing the number of test cases. For each test case:
- The first line provides elements of the BST in level order, with '-1' denoting null nodes.
- The second line gives the integer ‘K’, the target sum value.

Output:

For each test case, output a single line containing 'true' or 'false'.

Example:

Input:  
20 10 35 5 15 30 42 -1 13 -1 -1 -1 -1 -1 -1 -1
K = 45
Output:
true

Constraints:

  • 1 <= T <= 5
  • 1 <= N <= 10^3
  • 0 <= DATA <= 10^9
  • 1 <= K <= 10^9

Note:

The input for the tree should be a single line with values separated by spaces. Null nodes are represented as '-1'. Implement the function and logic, as output handling is already managed.
AnswerBot
4mo

Check if there exist two unique elements in a BST that sum up to a target value 'K'.

  • Traverse the BST in-order to get a sorted array of elements.

  • Use two pointers approach to find the pair sum in the so...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at VMware Software

Q. Reverse the String Problem Statement You are given a string STR which contains a...read more
Q. What are the stages in the Software Development Life Cycle?
Q. Common Elements in Three Sorted Arrays Given three sorted arrays A, B, and C of ...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits