• Related Questions & Answers

Two Sum BSTs in C++

C++Server Side ProgrammingProgramming

Suppose we have two binary search trees, we have to return True iff there is a node in the first tree and a node in the second tree and sum of these nodes is a given integer target. So if the tree is like −

and target is 5, then the result is true.

To solve this, we will follow these steps −

  • Define a map s
  • define a method called check(), this will take node, target and nodeNumber, this will work as follows −
  • if node is valid, then return false
  • curr := value of node, req := target – curr
  • if req is present in s and s[req] is not nodeNumber, then return true
  • s[curr] := nodeNumber
  • return check(left of node, target, nodeNumber) OR check(right of node, target, nodeNumber)
  • In the main method, we will set −
  • flag := check(root1, target, 1)
  • return check(root2, target, 2)


Let us see the following implementation to get better understanding −

class Solution {
   map <int,int> s;
   bool check(TreeNode* node, int target,int nodeNumber){
      if(!node)return false;
      int curr = node->val;
      int req = target - curr;
      if(s.find(req)!=s.end() &&s[req]!=nodeNumber)return true;
      return check(node->left,target,nodeNumber) || check(node->right,target,nodeNumber);
   bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
      bool flag = check(root1,target,1);
      return check(root2,target,2);




Published on 17-Mar-2020 11:19:52