Question

Exercise 1: BSTree operations For this exercise you'll implement three additional methods in the binary search...

Exercise 1: BSTree operations

For this exercise you'll implement three additional methods in the binary search tree data structure completed in class, so that you have an opportunity to practice both using the recursive pattern covered in class and navigating the binary tree structure.

The methods you'll implement are:

  1. count_less_than: takes an argument x, and returns the number of elements in the tree with values less than x
  2. successor: takes an argument x, and returns the smallest value from the tree that is larger than x (note that x itself does not need to be in the tree); if there are no values larger than x, returns None
  3. descendants: takes an argument x, and returns all descendants of x in the tree (i.e., all values in the subtree rooted at x), ordered by value; if x has no descendants or does not exist in the tree, returns an empty list

The cell below contains the (read-only) BSTree implementation from lecture. Beneath that is the cell containing the methods you will be implementing, followed by unit test cells.

In [ ]:

class BSTree:
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
  
def __init__(self):
self.size = 0
self.root = None

def __contains__(self, val):
def contains_rec(node):
if not node:
return False
elif val < node.val:
return contains_rec(node.left)
elif val > node.val:
return contains_rec(node.right)
else:
return True
return contains_rec(self.root)

def add(self, val):
assert(val not in self)
def add_rec(node):
if not node:
  return BSTree.Node(val)
elif val < node.val:
return BSTree.Node(node.val, left=add_rec(node.left), right=node.right)
else:
return BSTree.Node(node.val, left=node.left, right=add_rec(node.right))
self.root = add_rec(self.root)
self.size += 1
  
def __delitem__(self, val):
assert(val in self)
def delitem_rec(node):
if val < node.val:
node.left = delitem_rec(node.left)
return node
elif val > node.val:
node.right = delitem_rec(node.right)
return node
else:
if not node.left and not node.right:
return None
elif node.left and not node.right:
return node.left
elif node.right and not node.left:
return node.right
else:
# remove the largest value from the left subtree as a replacement
# for the root value of this tree
t = node.left # refers to the candidate for removal
if not t.right:
node.val = t.val
node.left = t.left
else:
n = t
while n.right.right:
n = n.right
t = n.right
n.right = t.left
node.val = t.val
return node
  
self.root = delitem_rec(self.root)
self.size -= 1

def __iter__(self):
def iter_rec(node):
if node:
yield from iter_rec(node.left)
yield node.val
yield from iter_rec(node.right)
  
return iter_rec(self.root)
  
def __len__(self):
return self.size
  
def pprint(self, width=64):
"""Attempts to pretty-print this tree's contents."""
height = self.height()
nodes = [(self.root, 0)]
prev_level = 0
repr_str = ''
while nodes:
n,level = nodes.pop(0)
if prev_level != level:
prev_level = level
repr_str += '\n'
if not n:
if level < height-1:
nodes.extend([(None, level+1), (None, level+1)])
repr_str += '{val:^{width}}'.format(val='-', width=width//2**level)
elif n:
if n.left or level < height-1:
nodes.append((n.left, level+1))
if n.right or level < height-1:
nodes.append((n.right, level+1))
repr_str += '{val:^{width}}'.format(val=n.val, width=width//2**level)
print(repr_str)
  
def height(self):
"""Returns the height of the longest branch of the tree."""
def height_rec(t):
if not t:
return 0
else:
return max(1+height_rec(t.left), 1+height_rec(t.right))
return height_rec(self.root)

class BSTree(BSTree):
def count_less_than(self, x):
=============your code here======================
  
def successor(self, x):
    =============your code here======================
  
  
def descendants(self, x):
   =============your code here======================
  

Test cases...

t = BSTree()
for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:
t.add(x)
  
assert t.count_less_than(6) == 6
assert t.count_less_than(0) == 0
assert t.count_less_than(9) == 9
assert t.count_less_than(100) == 10
assert t.count_less_than(-100) == 0

t = BSTree()
for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:
t.add(x)

assert t.successor(6) == 7
assert t.successor(6.5) == 7
assert t.successor(4) == 5
assert t.successor(5) == 6
assert t.successor(8) == 9
assert t.successor(-1) == 0
assert t.successor(9) is None
assert t.successor(10) is None

t = BSTree()
for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:
t.add(x)

assert t.descendants(6) == [0, 1, 2, 3, 4, 5, 7, 8, 9]
assert t.descendants(3) == [0, 1, 2, 4, 5]
assert t.descendants(7) == [8, 9]
assert t.descendants(1) == [0, 2]
assert t.descendants(0) == []
assert t.descendants(8) == []
assert t.descendants(100) == []
assert t.descendants(-100) == []

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note:

  • "Screen shot of the code" for better understanding.
  • "Code to copy" for run the program in your IDE.
  • Please follow the code indentation properly to avoid indentation errors.

Code Image:

Sample Output:

Code to Copy:

#Implementation of BSTree class

class BSTree:

    #Implementation of Node class

    class Node:

        #Implementation of __init__

        def __init__(self, val, left=None, right=None):

            self.val = val

            self.left = left

            self.right = right

           

    #Implementation of __init__

    def __init__(self):

        self.size = 0

        self.root = None

    #Imlementation of __contains__ method

    def __contains__(self, val):

        #Implementaion of contains_rec method

        def contains_rec(node):

            #check through if statement

            #node is exist or not

            if not node:

                return False

            #otherwise check val is less than

            #node.val

            elif val < node.val:

                #call contains_rec method in recursive approach

                return contains_rec(node.left)

            #otherwise check val is greater than

            #node.val

            elif val > node.val:

                return contains_rec(node.right)

            else:

                #otherwise return true

                return True

           

        #call contains_rec method in recursive approach

        return contains_rec(self.root)

    #Implemetation of add method

    def add(self, val):

        #call assert method

        assert(val not in self)

        #Implementation of add_rec method

        #with parameter type node

        def add_rec(node):

            #check node or not

            if not node:

                #call the BSTree.Node(val) method

                return BSTree.Node(val)

            #check val is less than node.val or not

            elif val < node.val:

                #call the BSTree.Node method with parameters

                return BSTree.Node(node.val, left=add_rec(node.left), right=node.right)

            else:

                #call the BSTree.Node method with parameters

                return BSTree.Node(node.val, left=node.left, right=add_rec(node.right))

           

        #assign the return value of the add_rec(self.root) function

        self.root = add_rec(self.root)

       

        #increment the self.size by 1

        self.size += 1

    #Implementation of __delitem__ method with parameters

    def __delitem__(self, val):

        #call assert method

        assert(val in self)

        #Implementation of delitem_rec method

      def delitem_rec(node):

            #check val is less than node.val or not

            if val < node.val:

                #assign return value of delitem_rec function to node.left

                node.left = delitem_rec(node.left)

                return node

            #check val is greater than node.val or not

            elif val > node.val:

                #assign return value of delitem_rec function to node.right

                node.right = delitem_rec(node.right)

                #return node

              return node

            else:

                #check node.left and node.right exist or not

                if not node.left and not node.right:

                    return None

                #other wise check node.left and node.right exist or not

                elif node.left and not node.right:

                    #return node.left

                    return node.left

                #other wise check node.left and node.right exist or not

                elif node.right and not node.left:

                    #return node.right

                    return node.right

                else:

                    # remove the largest value from the left subtree as a replacement

                    # for the root value of this tree

                    t = node.left # refers to the candidate for removal

                    #check t.right or not

                    if not t.right:

                        #assign t.val to node.val

                        node.val = t.val

                        #assign t.left to node.left

                        node.left = t.left

                    else:

                        #assign t to n

                        n = t

                        #Iterate the loop upto n.right.right

                        while n.right.right:

                            #assign n.right to n

                            n = n.right

                        #assign n.right to t

                        t = n.right

                        #assign t.left to n.right

                        n.right = t.left

                        #assign t.val to node.val

                        node.val = t.val

                    #return node

                    return node

        #self.root contains the return value of delitem_rec(self.root)

        self.root = delitem_rec(self.root)

        #decrement self.size by 1

        self.size -= 1

    #Implementation of __iter__ method

    def __iter__(self):

        #Implementation of iter_rec method with

        #paremeter node

        def iter_rec(node):

            #check node exist or not

            if node:

                #call iter_rec(node.left) through yield

                yield from iter_rec(node.left)

                #call node.val through yield

                yield node.val

                #call iter_rec(node.right) through yield

                yield from iter_rec(node.right)

        #return the iter_rec(self.root)

        return iter_rec(self.root)

    #Implementation of __len__ method

    def __len__(self):

        #return the self.size

        return self.size

    #Implementation of pprint method

    def pprint(self, width=64):

        """Attempts to pretty-print this tree's contents."""

        height = self.height()

        #store the nodes

        nodes = [(self.root, 0)]

        #Declare prev_level and assign 0

        prev_level = 0

        repr_str = ''

        #Iterate the loop

        while nodes:

            #assign return values of pop method

            # to n,level

            n,level = nodes.pop(0)

            #check prev_level is not equal to level or not

            if prev_level != level:

                #assign level to prev_level

                prev_level = level

                repr_str += '\n'

            if not n:

                #check level < height-1 or not

                if level < height-1:

                    #add the values to nodees

                    nodes.extend([(None, level+1), (None, level+1)])

                #add string to repr_str

                repr_str += '{val:^{width}}'.format(val='-', width=width//2**level)

            elif n:

                if n.left or level < height-1:

                    #append the values to nodes.

                    nodes.append((n.left, level+1))

                if n.right or level < height-1:

                    #append the values to nodes.

                    nodes.append((n.right, level+1))

                #add string to repr_str

                repr_str += '{val:^{width}}'.format(val=n.val, width=width//2**level)

        #Display statement

        print(repr_str)

     #Implementation of height method

    def height(self):

        """Returns the height of the longest branch of the tree."""

        #Implementation of height_rec method

        def height_rec(t):

            #check t or not

            if not t:

                #return value 0

                return 0

            else:

                #otherwise return max(1+height_rec(t.left), 1+height_rec(t.right))

                return max(1+height_rec(t.left), 1+height_rec(t.right))

       #call height_rec in recursive manner

        return height_rec(self.root)

    #Implementaion of count_less_than method

    #with an argument x

    def count_less_than(self, x):

        #Implementation of count_help function

        #with parameter node and x

        def count_help(node, x):

            # check node exist or not

            if not node:

                #return value 0

                return 0

            #check node.val is less than x

            if(node.val<x):

                # then

                # increment count_help(node.left, x) + count_help(node.right, x)

                # value by 1

                return (1 + count_help(node.left, x) + count_help(node.right, x))

            else:

                # left tree of BSTree exist or not

                return(count_help(node.left, x))

        #check with root node of BSTree

        return count_help(self.root, x)

    #Implementation of successor method with

    #parameter x

    def successor(self, x):

        def successor_help(node, x):

            # check with node

            if not node:

                #return the maximum val

                return 1000000

            #check with node.val is greater then x or not

            if(node.val>x):

                #call min(node.val, successor_help(node.left,x)) method

                return min(node.val, successor_help(node.left,x))

            #check with node.val is less than or x or not

            elif(node.val<x):

                #call successor_help in recursive manner

                return successor_help(node.right,x)

        #result contains the return value of successor_help function

        result = successor_help(self.root,x)

        # check there is no value is greater than return the

        #result other wise return None

        if(result==1000000):

            return None

        elif result!=1000000:

            #return the result

            return result;

    #Implementation of descendants method    

    def descendants(self, x):

        #Declare result used to store the descendants values

        result = []

        #Implementation of indescendantTraversal method

        # which traversals sort the descendents of BSTree

        def indescendantTraversal(node, k):

            #check node exist or not

            if not node:

                return

            #call the indescendantTraversal method with parameter

            #node.left and k in recursive manner

            indescendantTraversal(node.left,k)

            #check node.val is not equal to k

            if node.val != k:

                #append the node.val to result

                result.append(node.val)

            #call indescendantTraversal in recursive manner

            indescendantTraversal(node.right,k)

call the output statements:

>>> #create an object for BSTree class

# and initailize the BSTree class object

t = BSTree()

>>> #Iterate the list of values

for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:

    #add to the t

    t.add(x)

>>> #check wheter condition is returns true or false

assert t.count_less_than(6) == 6

>>> #Display statement

print(t.count_less_than(6) == 6)

>>>

>>> #check wheter condition is returns true or false

assert t.count_less_than(0) == 0

>>> #Display statement

print(t.count_less_than(0) == 0)

>>> #check wheter condition is returns true or false

assert t.count_less_than(9) == 9

>>> #Display statement

print(t.count_less_than(9) == 9)

>>>

#check wheter condition is returns true or false

assert t.count_less_than(100) == 10

>>> #Display statement

print(t.count_less_than(100) == 10)

>>> #check wheter condition is returns true or false

assert t.count_less_than(-100) == 0

>>> #Display statement

print(t.count_less_than(-100) == 0)

>>>

>>>

>>> #create an object for BSTree class

# and initailize the BSTree class object

t = BSTree()

>>> #Iterate the list of values

for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:

    #add to the t

    t.add(x)

>>> #Display statement

print(t.successor(6) == 7)

>>> #Display statement

print(t.successor(6) == 7)

>>> #Display statement

print(t.successor(6) == 7)

>>> #Display statement

print(t.successor(4) == 5)

>>> #Display statement

print(t.successor(5) == 6)

>>> #Display statement

print(t.successor(8) == 9)

>>> #Display statement

print(t.successor(-1) == 0)

True

>>> #Display statement

print(t.successor(9) is None)

>>> print(t.successor(9) is None)

>>>

>>> #create an object for BSTree class

# and initailize the BSTree class object

t = BSTree()

>>> #Iterate the list of values

for x in [6, 3, 5, 4, 7, 1, 2, 9, 8, 0]:

    #add to the t

    t.add(x)

   

>>>

print( t.descendants(6) == [0, 1, 2, 3, 4, 5, 7, 8, 9])

>>> print(t.descendants(3) == [0, 1, 2, 4, 5])

>>> print( t.descendants(7) == [8, 9])

>>> print(t.descendants(1) == [0, 2])

>>> print(t.descendants(0) == [])

>>>

print(t.descendants(8) == [])

>>>

print(t.descendants(100) == [])

>>> print(t.descendants(-100) == [])

>>>

Add a comment
Know the answer?
Add Answer to:
Exercise 1: BSTree operations For this exercise you'll implement three additional methods in the binary search...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (Please help me with Coding in Python3) AVLTree complete the following implementation of the balanced (AVL)...

    (Please help me with Coding in Python3) AVLTree complete the following implementation of the balanced (AVL) binary search tree. Note that you should not be implementing the map-based API described in the plain (unbalanced) BSTree notebook — i.e., nodes in the AVLTree will only contain a single value. class AVLTree: class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def rotate_right(self): n = self.left self.val, n.val = n.val, self.val self.left, n.left, self.right, n.right...

  • Python question. How do i make this code work? im trying to print the value of...

    Python question. How do i make this code work? im trying to print the value of the nodes using the level order trasversal class Node: def __init__(self, x): self.val = x self.left = None self.right = None class BinarySearchTree: def insertNode(self, value): self.root = self._insert(self.root, value)    def levelOrderTraversal(self, root): if root is None: return [] result, current = [], [root] while current: next_level, vals = [], [] for node in current: vals.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) current...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method...

    Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method in the code file shared with you and test it in the main to get the element at index 3 of mylist2 . class Node: def __init__(self, e): self.element = e self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 def addFirst(self, e): newNode = Node(e) newNode.next = self.head self.head = newNode self.size = self.size + 1...

  • Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. Note that as discussed in the video lecture, the index range of the array implementation of a heap is 1:n, NOT 0:n-1 • parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None •...

  • Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - ...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. - parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None - leftChild(index) returns the value of the left child of heap[index], returns None if there is no value - rightChild(index) returns...

  • PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a...

    PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a class called MyTree with the methods __init__(x), getLeft(), getRight(), getData(), insert(x) and getHeight(). Each child should itself be a MyTree object. The height of a leaf node should be zero. The insert(x) method should return the node that occupies the original node's position in the tree. Create a class called MyBST that extends MyTree. Override the method insert(x) to meet the definitions of a...

  • C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree...

    C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree methods (bst.cpp) for the binary search tree provided in the header file. Test your implementation with the included test. bst.h bst_test.cpp Note: Your implementation must correspond to declarations in the header file, and pass the test. Do not modify these two. I will compile your code against these. If the compilation fails, you will get down vote. bst.h #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <string>...

  • Previous code: class BinarySearchTree: def __init__(self, data): self.data = data self.left = None self.right = None de...

    Previous code: 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 traverse(root,order):...

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT