1

My homework needs me to sum all numbers under the given value in a BST. However, I had no idea how to do it. Appreciate for any help.

class BinarySearchTree:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
    def search(self, find_data):
        if self.data == find_data:
            return self
        elif find_data < self.data and self.left != None:
            return self.left.search(find_data)
        elif find_data > self.data and self.right != None:
            return self.right.search(find_data)
        else:
            return None 
    def get_left(self):
        return self.left
    def get_right(self):
        return self.right
    def set_left(self, tree):
        self.left = tree
    def set_right(self, tree):
        self.right = tree
    def set_data(self, data):
        self.data = data
    def get_data(self):
        return self.data

def create_new_bst(lst):
    #creates a new tree with root node 55, and then inserts all the
    #remaining values in order into the BST


def sum_beneath(t, value):
    # don't know how to do


t = create_new_bst([55, 24, 8, 51, 25, 72, 78])
result = sum_beneath(t, 72)
print('Sum beneath 72 =', result)# should show 'Sum beneath 72 = 78'

I'm very new to BST so I really have no idea on how to start and do this question.

def insert(self, new_data):#can I just call this function in 'create_new_bst'?
       if self.data:
            if new_data < self.data:
                if self.left is None:
                    self.left = BinarySearchTree(new_data)
                else:
                    self.left.insert(new_data)
            elif new_data > self.data:
                if self.right is None:
                    self.right = BinarySearchTree(new_data)
                else:
                    self.right.insert(new_data)
        else:
            self.data = data
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Victoriavv
  • 93
  • 1
  • 9
  • Please add your code for `create_new_bst` as well – Devesh Kumar Singh May 23 '19 at 07:21
  • You will need to recursively return the sum of subtree values. For a leaf node, it returns its own value. Other nodes will return their own value plus sum of left subtree plus sum of right subtree. Since this sort of method needs the BST object and not just the data (`72` in your case), you'll have to get that using `search` first. – shriakhilc May 23 '19 at 07:26
  • You need to first look for the tree, and then add the subtrees reccursively (such as: return current + sum(sub_tree_left + sub_tree_right) – BlueSheepToken May 23 '19 at 07:37
  • But if the value is not the root do I still have to sum the left and right subtree? Because I only need the sum that's under the value.For example, 72 should be at the right subtree and only 78 is under so it'll just return 78. – Victoriavv May 23 '19 at 07:57
  • @Victoriavv Yes, you need to find your tree first, I tried to write the code without filling the blank (the code is working, I tested it) – BlueSheepToken May 23 '19 at 08:05
  • Thanks I'll give it a try now!! @BlueSheepToken – Victoriavv May 23 '19 at 08:15

2 Answers2

0

Ok, as this is an exercise, I won't fill everything, but I will try to give you an idea of how it should be done:

You need to create your tree, in a simple way you can do this:

def create_new_bst(lst):
    tree = BinarySearchTree(tree[0])
    # And then, using the insert method, which is correct, add your nodes in the tree
    return tree

First, you need to find Your subtree with the root 72

# Replace the pass with the appropriate code

def find_subtree(tree, value):
    if value == tree.data: # This is found yeah !
         pass
    if value > tree.data: # Ok, this is not our data, we should look recursively in one of the children (I will not tell you which one). Maybe we can use find_subtree reccursively?
         pass
    if value < tree.data: # Same as above, but maybe we should look in the other child
         pass
    raise ValueError("Not found value " + str(value)) # Nothing has been found.

Now, you found the tree with my_tree = find_subtree(t, 72), you should just sum the left tree (if it exists) and the right tree (if it exists)

def sum_beneath(t, value):
    my_tree = find_subtree(t, value)
    s = 0
    if my_tree.left is not None:
         s += my_tree.left.sum_tree()
    if my_tree.right is not None:
         s += my_tree.right.sum_tree()
    return s

Let's define the sum_tree method (in the class)! :)

def sum_tree(self):
    ans =  self.data
    # Add the left sum reccursively
    # Add the right sum reccursively
    return ans

I hope this will help you to understand the concept of BST. If you need help do not hesitate to comment

BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
0

It's quite an interesting problem to find the sum of nodes under a specific value, we can think of this of something like searching and transversing problem, there can be various ways to do this, but I can think of this something like-

  1. Doing a binary search for the node.
  2. Doing an (In-order, Post-Order or Pre-order) transversal, and saving the results of the returned nodes' values i.e. summing them up.

the big O time complexity I can think of should be something like-

for an nth node in the BST, log(n) should be the search time, then for the transversal (In-order, Post-Order or Pre-order), it should be m-n, where (m is the total number of nodes)

therefore, the total will be, (log(n) + m - n) ~ O(M).

P.hunter
  • 1,345
  • 2
  • 21
  • 45