Problem 3

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Professor name:

Dr. Keyhanopur

Student name: Amirhossein Mohajersoltani


Student number: 401152577

Data Structures and Algorithms final project


Topic3
Binary Search Tree (BST):
A binary search tree is a hierarchical data structure in which each node has at most two children. It
follows the ordering property where all elements in the left subtree of a node are less than the node's
key, and all elements in the right subtree are greater.

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.

Finding kth Largest Element:


The ‘kth_largest_bst’ function recursively finds the kth largest element. It efficiently uses the ‘count’
attribute to determine subtree sizes and decides whether to continue the search in the right or left
subtree based on a comparison with the desired k value.

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:

# Create an empty Binary Search Tree

root = None

# Insert elements into the BST

elements = [20, 15, 25, 10, 18, 22, 30]

for element in elements:

root = insert(root, element)


# Find the 3rd largest element

k_value = 3

kth_largest = kth_largest_bst(root, k_value)

print(f"The {k_value}th largest element in the BST is: {kth_largest}")

Output:

The 3rd largest element in the BST is: 22

In this example, the code creates a BST, inserts elements, and finds the 3rd largest element, which is 22
in this case.

You might also like