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.
Be the first one to answer
Add answer anonymously...
VMware Software 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