Created
June 18, 2021 10:24
-
-
Save foxyseta/407d96215fe2cede7b5a1f67b8417d8a to your computer and use it in GitHub Desktop.
A minimal Python implementation for binary trees
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# University of Bologna | |
# First cycle degree in Mathematics | |
# 07276 - Computer Science | |
# | |
# Stefano Volpe #969766 | |
# 06/18/2021 | |
# | |
# trees.py: tree class implementation | |
class tree: | |
def __init__(self, label=None, sx=None, dx=None): | |
self.__label = label | |
self.__sx = sx | |
self.__dx = dx | |
if label is not None: | |
if sx is None: | |
self.__sx = tree() | |
self.__dx = tree() | |
def label(self): | |
return self.__label | |
def first_child(self): | |
return self.__sx | |
def second_child(self): | |
return self.__dx | |
def is_empty(self): | |
return self.__label is None | |
def is_leaf(self): | |
return not self.is_empty() and self.__sx.is_empty() \ | |
and self.__dx.is_empty() | |
# def __str__(self): # The default implementation calls object.__repr__() | |
def __repr__(self): | |
res = "tree(" | |
if not self.is_empty(): | |
res += self.label().__repr__() | |
if not self.is_leaf(): | |
res += ", " + self.first_child().__repr__() + ", " \ | |
+ self.second_child().__repr__() | |
return res + ")" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment