Skip to content

Instantly share code, notes, and snippets.

@jmccardle
Created August 18, 2023 01:21
Show Gist options
  • Save jmccardle/62207e09f1399c1977dbd3ce9e2f84ae to your computer and use it in GitHub Desktop.
Save jmccardle/62207e09f1399c1977dbd3ce9e2f84ae to your computer and use it in GitHub Desktop.
class BinaryNode:
__slots__ = ("value", "left", "right")
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return f"<BinaryNode value={self.value}; {1 if self.left else 0 + 1 if self.right else 0} children>"
def inorder(self):
if self.left:
for value in self.left.inorder():
yield value
yield self.value
if self.right:
for value in self.right.inorder():
yield value
def preorder(self):
yield self.value
if self.left:
for value in self.left.preorder():
yield value
if self.right:
for value in self.right.preorder():
yield value
def postorder(self):
if self.left:
for value in self.left.postorder():
yield value
if self.right:
for value in self.right.postorder():
yield value
yield self.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment