I'm trying to implement a binary search tree for storing student data such as first name, last name, id, and GPA and apply some strategy patterns to them. I'm not able to understand how to insert students' data objects in the BST. Is there any resource or websites for reference?
CodePudding user response:
A Binary search tree inserts elements by starting from the top of the tree, comparing the node to insert with the current node, then deciding whether to place it to the left or to the right of the current node, going down another level if that node to the left or right is already taken. This is easy for built-in data types, but for custom objects you have to define your own way to make the comparison so that those left-right decisions can be made.
There is no built-in data structure for binary search trees in Python, but they are relatively easy to implement. This article provides great information on how to do that:
https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
As for your situation, you'll of course need a Student
class, which will be used as Nodes
in the BST. In order to insert students into a BST, you have to be able to compare one Student
to another. Since it sounds like each object will have a unique ID, that would definitely be the easiest way to compare them. You can do this by overloading the comparison operators like <
and ==
in python, which is explained here:
https://www.tutorialspoint.com/How-to-overload-Python-comparison-operators
In all, you may end up with a Student
class looking something like this:
class Student:
def __init__(self, id, first_name, last_name, gpa):
self.id=id
self.first_name=first_name
self.last_name=last_name
self.gpa=gpa
def __eq__(self, other):
return self.id == other.id
def __lt__(self, other):
return self.id < other.id
Then you should be able to insert and lookup Student objects in your BST implementation.