Created
December 16, 2019 08:36
-
-
Save neptunius/0af2570ac8d63bfb7b0bcdd56bca02db to your computer and use it in GitHub Desktop.
Helper method to create a printable visual string representation of a binary search tree
This file contains hidden or 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 BinaryTreeNode: | |
def __init__(self, data): | |
self.data = data | |
self.left = None | |
self.right = None | |
class BinarySearchTree: | |
def __init__(self): | |
self.root = None | |
# ... | |
def __str__(self, node=None): | |
"""Return a visual string representation of this binary search tree. | |
Performs depth-first traversal starting at the given node or root.""" | |
if node is None: | |
if self.is_empty(): # Special case | |
return 'root -> None' | |
else: # Start recursion at root node | |
return '\n'.join(self.__str__(self.root)) | |
strings = [] # Accumulate separate strings since we need to pad them | |
if node.right is not None: # Descend right subtree, if it exists | |
for right_string in self.__str__(node.right): | |
# Left-pad strings and replace ambiguous root with right link | |
strings.append(5 * ' ' + right_string.replace('->', '/-', 1)) | |
strings.append('-> ({})'.format(repr(node.data))) # This node's string | |
if node.left is not None: # Descend left subtree, if it exists | |
for left_string in self.__str__(node.left): | |
# Left-pad strings and replace ambiguous root with left link | |
strings.append(5 * ' ' + left_string.replace('->', '\\-', 1)) | |
return strings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment