Two sum in BSTs in JavaScript


Problem:

We are required to write a JavaScript function that takes in the roots of two binary search trees, root1 and root2, as the first and the second argument respectively. The third argument to the function is number, target.

Our function should return True if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target, false otherwise.

For example, if the input to the function is −

const target = 23;

BSTs

Then the output should be −

const output = true;

Output Explanation:

Because there exists 6 in the first tree and 17 in the second, whose sum is 23.

Example

The code for this will be −

 Live Demo

class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      // root of a binary seach tree
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const tree1 = new BinarySearchTree();
tree1.insert(1);
tree1.insert(3);
tree1.insert(4);
tree1.insert(2);
tree1.insert(4);
tree1.insert(5);
tree1.insert(6);
const tree2 = new BinarySearchTree();
tree2.insert(9);
tree2.insert(6);
tree2.insert(11);
tree2.insert(3);
tree2.insert(8);
tree2.insert(10);
tree2.insert(17);
const twoSumBSTs = (root1, root2, target) => {
   if(root1 == null || root2 == null) return false;
   if(root1.data + root2.data == target) return true;
   if(root1.data + root2.data < target) {
      return twoSumBSTs(root1.right, root2, target) || twoSumBSTs(root1, root2.right, target);
   }else{
      return twoSumBSTs(root1.left, root2, target) || twoSumBSTs(root1,
      root2.left, target);
   };
};
const target = 23;
console.log(twoSumBSTs(tree1.root, tree2.root, target));

Output

And the output in the console will be −

true

Updated on: 07-Apr-2021

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements