696. Two Sum BSTs

Given two binary search trees (BSTs), determine if there exists a pair of values, one from each tree, that sums up to a given integer target.

Example 1:

Input: root 1: [2, 1, 4], root 2: [1, 0, 3], target: 5

Output: true

Explanation: Pairs (2,3) or (4,1) sum to 5.

Example 2:

Input: root 1: [0, -10, 10], root 2: [5, 1, 7, 0, 2], target: 18

Output: false

Explanation: No pair of values sum to 18.

Now Your Turn!

Pick the correct output for the given input

Input: root 1: [5, 3, 7, 2, 4], root 2: [6, 1, 8, 5], target:10

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

The number of nodes in each tree is in the range [1,5000].

-109 <= Node.val, target <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
//Your Code Goes Here
}
};
Test Case

Input:

Root1
Root2
Target