Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Two Sum from BST (Main Thread)

Here is the interview question prompt, presented for reference.

This problem is a fun combination of the famous Two Sum problem combined with a binary search tree. Given the root of a binary search tree, and a target integer K, return true if there exist two nodes in the said tree whose sum equals K. If no pair fits this match, return false.

Say we are given this tree:

/***

  Input:
    5    
   / \     
  3   8
 /        
1

***/

Each node is defined in the following manner:

class Node {
    constructor(val) {
        this.value = val;
        this.left = null;
        this.right = null;
    }
}

And thus the below setup and execution code should hold true:

const root = new Node(5);
root.left = new Node(3);
root.right = new Node(8);
root.left.left = new Node(1);

const target = 11;

twoSumFromBST(root, target);
// true because 3 + 8 = 11

Constraints

  • Number of vertices in the tree <= 100000
  • The values in the vertices will be between -100000 and 1000000
  • The target value will be between -100000 and 100000
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)

You can see the full challenge with visuals at this link.

Challenges • Asked over 6 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for Two Sum from BST.