Two-Sum BST

Problem

Given a binary search tree T, where each node contains a positive integer, and an integer K, you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.

For example:

Input 1: 

T :       10
         / \
        9   20

K = 19

Return: True

Solution

class Solution():

    def t2Sum(self, root, k):

        if self.helper(root, k, {})==True:
            return 1
        else:
            return 0

    def helper(self, root, k, store):
        
        if root is None:
            return 
        
        subtractedValue = k - root.val

        if subtractedValue not in store:
            store[root.val] = subtractedValue
        else:
            return True
        return self.helper(root.left, k, store) or self.helper(root.right, k, store)
        
#Time: O(n)
#Space: O(h)

Last updated

Was this helpful?