Skip to content

Instantly share code, notes, and snippets.

@StephanieSunshine
Created February 5, 2022 09:53
Show Gist options
  • Save StephanieSunshine/27226f2b98e6205f2fcb65dbd84a2f08 to your computer and use it in GitHub Desktop.
Save StephanieSunshine/27226f2b98e6205f2fcb65dbd84a2f08 to your computer and use it in GitHub Desktop.
Improved binary tree in Python
#!/usr/bin/env python3
# MIT License 2022 -- Stephanie Sunshine
# created as an example to my students of an improved binary tree and traverse (sort)
class FancyNode:
def __init__(self, data = 0, count = 0, left = None, right = None):
self.data = data
self.count = count
self.left = left
self.right = right
def add(self, number):
current_node = self
while True:
if current_node.data == number:
current_node.count += 1
return
if current_node.data < number:
if current_node.left == None:
current_node.left = FancyNode(number,1)
return
else:
current_node = current_node.left
continue
else:
if current_node.right == None:
current_node.right = FancyNode(number,1)
return
else:
current_node = current_node.right
continue
def Traverse(self):
output = []
if self.right != None:
output += self.right.Traverse()
for i in range(0,self.count):
output.append(self.data)
if self.left != None:
output += self.left.Traverse()
return output
x = FancyNode(50,1)
x.add(6)
x.add(20)
x.add(20)
x.add(100)
x.add(100)
print(x.Traverse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment