CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

CoCalc’s goal is to provide the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual use to large groups and classes.

| Download
Project: MAT 2540
Views: 75
Visibility: Unlisted (only visible to those who know the link)
Image: ubuntu2004
Kernel: Python 3 (Anaconda 2020)
#Class definition for a vertex in a tree class Vertex(): #Initializes a vertex with no children labelled "data" def __init__(self, data=""): self.data = data self.children = [] #Method for adding vertices to the tree as children of a specific vertex #Note, duplicates will be added def add(self, parent, child2): if self.data == parent: self.children.append(Vertex(child2)) else: for child in self.children: child.add(parent, child2) #Prints the content of a tree with indendation to show ancestry def printTree(self, s = "---"): print(s + self.data) s = " " + s for child in self.children: child.printTree(s) #Returns the preorder traversal of a tree as an array of Vertex objects def preorder(self, s = []): s.append(self.data) for child in self.children: child.preorder(s) return s #Returns the inorder traversal of a tree as an array of Vertex objects def inorder(self, s = []): if len(self.children) > 0: self.children[0].inorder(s) s.append(self.data) if len(self.children) > 1: for child in self.children[1:]: child.inorder(s) return s
t = Vertex('a')
t.add('a','b') t.add('a','c') t.add('c','d') t.add('c','e') t.add('b','f')
t.printTree()
---a ---b ---f ---c ---d ---e
t.preorder()
['a', 'b', 'f', 'c', 'd', 'e']
t.inorder()
['f', 'b', 'a', 'd', 'c', 'e']