Rank and Select operations in BST without size attribute

50 Views Asked by At

I want to compare the order statistics of three different data structures: sorted list, red-black tree, and binary search tree. I have successfully implemented the rank and select operations for the first two data structures, and I still need to implement them in the binary search tree. However, the task instructions require me to handle the size of the data structure without using the "size" attribute but instead using a "counting" inorder traversal. I'm not entirely sure what is meant by a "counting" inorder traversal. Does anyone have any ideas?

Below is the implementation of the ABR class representing the binary search tree:

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.parent = None


class ABR:
    def __init__(self):
        self.root = None

    def insert(self, key):
        y = None
        x = self.root
        z = Node(key)
        while x is not None:
            y = x
            if key <= x.key:
                x = x.left
            else:
                x = x.right
        z.parent = y
        if y is None:
            self.root = z
        elif key < y.key:
            y.left = z
        else:
            y.right = z
        return z

    def find_node(self, currentNode, key):
        if currentNode is None:
            return None
        elif key == currentNode.key:
            return currentNode
        elif key < currentNode.key:
            return self.find_node(currentNode.left, key)
        else:
            return self.find_node(currentNode.right, key)

    def inorder_traversal(self, node, result=None):
        if result is None:
            result = []
        if node is not None:
            self.inorder_traversal(node.left, result)
            result.append(node)
            self.inorder_traversal(node.right, result)
        return result

My idea was to implement a new function called count_inorder() that performs an inorder traversal while simultaneously counting the nodes, in the following way:

    def count_inorder(self, node):
        if node is None:
            return 0

        count = 1

        if node.left is not None:
            count += self.count_inorder(node.left)

        if node.right is not None:
            count += self.count_inorder(node.right)

        return count
0

There are 0 best solutions below