Junior — Senior
Checking the existence of a pair of nodes with sum k in a binary search tree
livecode
Task condition
Given a binary search tree (BST) and an integer k. Determine whether there are two distinct nodes in the tree such that their values sum up to k.
Example 1 Input: root = [5,3,6,2,4,null,7], k = 9 Output: true
Example 2 Input: root = [5,3,6,2,4,null,7], k = 28 Output: false
Constraints
- The total number of nodes is in the range from 1 to 10^4.
- Node values are in the range from -10^4 to 10^4.
- The tree is guaranteed to be a valid BST.
- The value of k is in the range from -10^5 to 10^5.
public 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;
}
}
class Solution {
public boolean findTarget(TreeNode root, int k) {
// Implement logic to find if two elements in BST sum up to k
}
}