Created
May 2, 2018 17:40
-
-
Save cal97g/18d21214a292e18cf065caa9be15cbf9 to your computer and use it in GitHub Desktop.
An implementation of a basic Binary Tree in Python. I thought it was quite elegant.
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 BinaryNode(object): | |
def __init__(self, name, left = None, right = None): | |
self.name = name | |
self.left = left | |
self.right = right | |
def set_root(self, obj): | |
self.name = obj | |
def insert_left(self, new_node): | |
if self.left == None: | |
self.left = BinaryNode(new_node) | |
else: | |
t = BinaryNode(new_node) | |
t.left = self.left | |
self.left = t | |
def insert_right(self, new_node): | |
if self.right == None: | |
self.right = BinaryNode(new_node) | |
else: | |
t = BinaryNode(new_node) | |
t.right = self.right | |
self.right = t | |
def __repr__(self): | |
return "BinaryNode({}, {}, {})".format(self.name, self.left, self.right) | |
right_sub_tree = BinaryNode(300, 600, 700) | |
left_sub_tree = BinaryNode(200, BinaryNode(400, 800, 900), 500) | |
full_tree = BinaryNode(100, left_sub_tree, right_sub_tree) | |
print(full_tree) | |
print(full_tree.left.right) | |
# BinaryNode(100, BinaryNode(200, BinaryNode(400, 800, 900), 500), BinaryNode(300, 600, 700)) | |
# 500 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment