Question

Recall the 2-sum problem which took an array of N integers and determined the number of...

Recall the 2-sum problem which took an array of N integers and determined the number of pairs that summed to 0. Now consider a 2-sum BST problem. Let B be a binary search tree with N integers as unique keys. Using only data structures and algorithms that have been discussed in this class, describe an algorithm that will return the number of pairs in B that add to 0. Analyze the space and runtime of your algorithm.

Homework Answers

Answer #1

We are given a BST(binary search tree) and we have to find the number of pairs in this BST with zero sum. Following is a approach to solve this:

Step 1: Create a hash table to store the minus of the node's value. This table is used to lookup for pairs with zero sum.

Step 2: Traverse the BST in any order(pre/post/in). Check if the node's value is present in the hash table. If yes, increment the count by 1.

Step 3: If the node's value is present in the hash, do not add it's value to the hash table to avoid the duplicate counting.

The time complexity of this approach is O(n) because we visit every node once.

The space complexity is also O(n) because we are creating a hash table. In the worst case, number elements in hash table would be equal to the number of nodes in the tree.

Following is the python code for this approach:

# Python program to count the number of pairs
# in a binary tree whose sum is
# equal to zero


count = 0 #gloal variable count

# Node class for creating a node in the binary tree
# with value, left and right attributes
class Node(object):
def __init__(self, value, left = None, right = None):
self.value = value
self.left = left
self.right = right
  


  
# This hash table stores the minus of the
# node's value
# used to lookup for pairs with zero sum
hash_table = set()
  

  
# this function is to count number of pairs with zero sum
# Does a pre-order traversal of the tree.However, the tree
# can be traversed in any order
def count_pairs(root):
global count
if root:
if root.value in hash_table:
count = count + 1
else:
hash_table.add(-root.value)
  
count_pairs(root.left)
count_pairs(root.right)
  
# This is the Main function and entry point of program
# acts as Driver function
# Creates a binary search tree and call the function
# to get the count and finally prints the count value
if __name__ == '__main__':
root = Node(5)
  
root.left = Node(3)
root.right = Node(7)
  
root.left.left = Node(-3)
root.left.right = Node(4)
  
root.right.left = Node(6)
root.right.right = Node(8)
  
count_pairs(root)
  
print(count)

The BST in the above program has 7 nodes with values -3, 3, 4, 5, 6, 7, 8.

So, it has only one pair (-3, 3) with zero sum.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Consider a binary search tree where each tree node v has a field v.sum which stores...
Consider a binary search tree where each tree node v has a field v.sum which stores the sum of all the keys in the subtree rooted at v. We wish to add an operation SumLE(K) to this binary search tree which returns the sum of all the keys in the tree whose values are less than or equal to K. (a) Describe an algorithm, SumLE(K), which returns the sum of all the keys in the tree whose values are less...
Problem Definition: Problem: Given an array of integers find all pairs of integers, a and b,...
Problem Definition: Problem: Given an array of integers find all pairs of integers, a and b, where a – b is equal to a given number. For example, consider the following array and suppose we want to find all pairs of integers a and b where a – b = 3 A = [10, 4, 6, 16, 1, 6, 12, 13] Then your method should return the following pairs: 4, 1 15, 12 13, 10 A poor solution: There are...
Using Tuples in python In this problem, you will be given an array A of integers...
Using Tuples in python In this problem, you will be given an array A of integers of fixed size N and an integer K and you have to find the number of tuples (i, j) such that the following properties are satisfied, ● A[i]*A[i+1]*A[i+2]...A[j-1]*A[j] < K ● -1 < i < N ● i < j + 1 Note that the array is 0-indexed. Input Format The first line will contain integers N and K separated by a single space....
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number...
1. Given an n-element array A, Algorithm X executes an O(n)-time computation for each even number in A and an O(log n)-time computation for each odd number in A. What is the best-case running time of Algorithm X? What is the worst-case running time of Algorithm X? 2. Given an array, A, of n integers, give an O(n)-time algorithm that finds the longest subarray of A such that all the numbers in that subarray are in sorted order. Your algorithm...
Suppose an array A stores n integers, each of which is in {0, 1, 2, ...,...
Suppose an array A stores n integers, each of which is in {0, 1, 2, ..., 99}. Which of the following sorting algorithms can sort A in O(n) time in the worst case? Question 16 options: A) merge sort B) counting sort C) quicksort D) None of these options is correct. E) insertion sort
Suppose that you want to add items to an array such that the items are always...
Suppose that you want to add items to an array such that the items are always ordered in ascending order; e.g., [1, 2, 2, 4, 5, 8, 9, 14, 32], and any duplicate values are adjacent to each other. We haven’t talked about sorting algorithms yet, so assume you want to be able to keep the items in the array in order without having to sort them. So for example, suppose you want to add the integer value 7 to...
Coin Change Problem) Given a list of positive integers c[0...n − 1], and a positive integer...
Coin Change Problem) Given a list of positive integers c[0...n − 1], and a positive integer v, decides whether we can use numbers from c[0...n − 1] to make a sum of v, allowing any particular number in the list to be used multiple times. Or, mathematically, this means that there exists non-negative integer coefficients, x0, x1, ..., xn−1, such that v = x0c[0] + x1c[1] + ...xn−1c[n − 1]. For example, given c[0...3] = {2, 4, 6, 10}, and...
The main goal is to implement two recursive methods, each is built to manipulate linked data...
The main goal is to implement two recursive methods, each is built to manipulate linked data structures. To host these methods you also have to define two utterly simplified node classes. 1.) Add a class named BinaryNode to the project. This class supports the linked representation of binary trees. However, for the BinaryNode class Generic implementation not needed, the nodes will store integer values The standard methods will not be needed in this exercise except the constructor 2.) Add a...
import java.util.ArrayList; /* Rules:         1. Allow Tester to iterate through all nodes using the...
import java.util.ArrayList; /* Rules:         1. Allow Tester to iterate through all nodes using the in-order traversal as the default.             This means, in Tester the following code should work for an instance of this class             called bst that is storing Student objects for the data:                 BinarySearchTree_Lab08<String> bst = new BinarySearchTree_Lab08<String>();                 bst.add("Man");       bst.add("Soda");   bst.add("Flag");                 bst.add("Home");   bst.add("Today");   bst.add("Jack");                ...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT