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: 74
Visibility: Unlisted (only visible to those who know the link)
Image: ubuntu2004
Kernel: SageMath 9.6

Binary Search Tree

class binaryTreeNode(): def __init__(self,data=None): self.data = data self.left = None self.right = None def printBinaryTree(self,s = '---'): if self.data: print(s+self.data) s = ' ' + s if self.left: self.left.printBinaryTree(s) if self.right: self.right.printBinaryTree(s) def insertWord(self,word): v = self while v.data: if word < v.data: if v.left: v = v.left else: v.left = binaryTreeNode() v = v.left else: if v.right: v = v.right else: v.right = binaryTreeNode() v = v.right v.data = word return self
wordList = ['mathematics','physics','geography', 'zoology','meteorology','geology', 'psychology','chemistry']
tree = binaryTreeNode()
for word in wordList: tree.insertWord(word)
tree.printBinaryTree()
---mathematics ---geography ---chemistry ---geology ---physics ---meteorology ---zoology ---psychology