Given a Balanced Binary Search Tree and a target sum, the task is to check if there exist a pair in BST with sum equal to the target sum. Any modification to the Binary Search Tree is not allowed.
[Naive Approach] Check Compliment for Every node - O(n * h) Time and O(h) Space
The idea is to traverse the BST and for each node and search for their compliment , that is (target - node value) in the BST. If the complement is found, return true. Otherwise, continue checking the left and right subtrees recursively. If no such pair is found by the end of traversal, return false.
Below is the implementation of the above approach:
Output
True
[Expected approach] Using Inorder Traversal - O(n) Time and O(n) Space
The idea is to create an auxiliary array and store the Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Now we can apply Two pointer technique to find the pair of integers with sum equal to target. (Refer Two sum for details).