Last active
October 3, 2020 03:22
-
-
Save seisvelas/9f1b802aa88a2b723159b9ab28781b26 to your computer and use it in GitHub Desktop.
Solution to programming challenge (print binary tree elements in order) from https://www.youtube.com/watch?v=OTfp2_SwxHk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinaryTree: | |
left = None | |
right = None | |
value = None | |
def __init__(self, *initial): | |
self.value = initial.pop(0) | |
for i in initial: | |
self.add(i) | |
def add(self, new_value): | |
if new_value > self.value: | |
if self.right is None: | |
self.right = BinaryTree(new_value) | |
else: | |
self.right.add(new_value) | |
elif new_value < self.value: | |
if self.left is None: | |
self.left = BinaryTree(new_value) | |
else: | |
self.left.add(new_value) | |
def ordered_print(self): | |
if self.left is not None: | |
self.left.ordered_print() | |
print(self.value) | |
if self.right is not None: | |
self.right.ordered_print() | |
def ordered_list(self): | |
lst = [] | |
if self.left is not None: | |
lst += self.left.ordered_list() | |
lst.append(self.value) | |
if self.right is not None: | |
lst += self.right.ordered_list() | |
return lst | |
# 1 | |
# / \ | |
# 0 2 | |
# / \ | |
# None 3 | |
root_node = BinaryTree(1, 2, 3, 0) | |
print(root_node.ordered_list()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Astute readers will notice we (fati and me did this because we couldn't sleep last night) didn't do the second part, which is printing them in order iteratively, without recursion.