Professional Documents
Culture Documents
Problem 3
Problem 3
Problem 3
Dr. Keyhanopur
TreeNode Class:
The ‘TreeNode’ class represents a node in the BST, containing a ‘key’ for the value, ‘left’ and ‘right’
pointers for children, and a ‘count’ attribute indicating the size of the subtree rooted at the node.
Insertion Operation:
The ‘insert’ function inserts a new element into the BST, maintaining the order. It recursively traverses
the tree, increments the ‘count’ for each visited node, and places the new node based on its key.
Time Complexity:
The average time complexity for finding the kth largest element is O(log n), where n is the number of
nodes in the BST. This efficiency is achieved by navigating the tree based on subtree sizes.
Space Complexity:
The space complexity is O(log n) due to recursion, with the maximum recursion depth limited by the
height of the BST.
Sample Output:
#python
# Example usage:
root = None
k_value = 3
Output:
In this example, the code creates a BST, inserts elements, and finds the 3rd largest element, which is 22
in this case.