Two Sum IV - Input is a BST in C++


Suppose we have a Binary Search Tree and one target value; we have to check whether there exist two elements in the BST such that their sum is equal to the given target or not.

So, if the input is like

then the output will be True.

To solve this, we will follow these steps −

  • Define an array v

  • Define a function inorder(), this will take root,

  • if root is null, then −

    • return

  • inorder(left of root)

  • insert value of root into v

  • inorder(left of root)

  • Define a function findnode(), this will take k,

  • n := size of v

  • while i < j, do −

    • t := v[i] + v[j]

    • if t is same as k, then −

      • return true

    • if t < k, then −

      • (increase i by 1)

    • Otherwise

      • (decrease j by 1)

  • return false

  • From the main method do the following −

  • inorder(root)

  • sort the array v

  • return findnode(k)

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = NULL;
         right = NULL;
      }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
         return;
      }
      else{
         q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class Solution {
public:
   vector<int> v;
   void inorder(TreeNode* root){
      if (root == NULL || root->val == 0)
         return;
      inorder(root->left);
      v.push_back(root->val);
      inorder(root->right);
   }
   bool findnode(int k){
      int n = v.size(), i = 0, j = n - 1;
      while (i < j) {
         int t = v[i] + v[j];
         if (t == k)
            return true;
         if (t < k)
            i++;
         else
            j--;
      }
      return false;
   }
   bool findTarget(TreeNode* root, int k){
      inorder(root);
      sort(v.begin(), v.end());
      return findnode(k);
   }
};
main(){
   Solution ob;
   vector<int> v = {5,3,6,2,4,NULL,7};
   TreeNode *root = make_tree(v);
   cout << (ob.findTarget(root, 9));
}

Input

{5,3,6,2,4,NULL,7},9

Output

1

Updated on: 11-Jun-2020

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements