Skip to content

Instantly share code, notes, and snippets.

@foxyseta
Created June 18, 2021 10:24
Show Gist options
  • Save foxyseta/407d96215fe2cede7b5a1f67b8417d8a to your computer and use it in GitHub Desktop.
Save foxyseta/407d96215fe2cede7b5a1f67b8417d8a to your computer and use it in GitHub Desktop.
A minimal Python implementation for binary trees
# 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