Given the root of a Binary Search Tree (BST) and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, otherwise return false.
k?Consider the below BST and k = 9:
5
/ \
3 6
/ \ \
2 4 7
Here, the sum of nodes 3 and 6 is 9, so the output should be true.
k.import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
// Function to find if there exist two elements in BST that sum up to k
public boolean findTarget(TreeNode root, int k) {
List<Integer> sortedList = new ArrayList<>();
inOrderTraversal(root, sortedList);
int left = 0, right = sortedList.size() - 1;
while (left < right) {
int sum = sortedList.get(left) + sortedList.get(right);
if (sum == k) {
return true;
} else if (sum < k) {
left++;
} else {
right--;
}
}
return false;
}
// Helper function for in-order traversal to get sorted list
private void inOrderTraversal(TreeNode root, List<Integer> sortedList) {
if (root == null) {
return;
}
inOrderTraversal(root.left, sortedList);
sortedList.add(root.val);
inOrderTraversal(root.right, sortedList);
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?