Skip to content

Instantly share code, notes, and snippets.

@santosh
Created June 1, 2019 08:47
Show Gist options
  • Save santosh/bc788569f661f1ea48e6601408bb146b to your computer and use it in GitHub Desktop.
Save santosh/bc788569f661f1ea48e6601408bb146b to your computer and use it in GitHub Desktop.
Implementation of binary tree in Python. #DataStructures
class Node:
"""
This Node class has been created for you.
It contains the necessary properties for the solution, which are:
- text
- next
"""
def __init__(self, data, value):
self.data = data
self.value = value
self.__left = None
self.__right = None
def set_right(self, node):
if isinstance(node, Node) or node is None:
self.__right = node
else:
raise TypeError("The 'right' node must be of type Node or None.")
def set_left(self, node):
if isinstance(node, Node) or node is None:
self.__left = node
else:
raise TypeError("The 'left' node must be of type Node or None.")
def get_right(self):
return self.__right
def get_left(self):
return self.__left
def print_details(self):
print("{}: {}".format(self.value, self.data))
class BinaryTree:
"""
This class is a binary tree implementation.
Don't modify class or method names, just implement methods that currently raise
a NotImplementedError!
"""
def __init__(self):
self.__root = None
def get_root(self):
return self.__root
def add(self, node):
# The root is None, so set the root to be the new Node.
if not self.__root:
self.__root = node
else:
# Start iterating over the tree.
marker = self.__root
while marker:
if node.value == marker.value:
raise ValueError("A node with that value already exists.")
elif node.value > marker.value:
if not marker.get_right():
marker.set_right(node)
return
else:
marker = marker.get_right()
else:
if not marker.get_left():
marker.set_left(node)
return
else:
marker = marker.get_left()
def find(self, value):
marker = self.__root
while marker:
if value == marker.value:
return marker
elif value > marker.value:
marker = marker.get_right()
else:
marker = marker.get_left()
raise LookupError("A node with value {} was not found.".format(value))
def print_inorder(self):
self.__print_inorder_r(self.__root)
def __print_inorder_r(self, current_node):
if not current_node:
return
self.__print_inorder_r(current_node.get_left())
print(current_node.print_details())
self.__print_inorder_r(current_node.get_right())
# See also:
# Linked List: https://gist.github.com/santosh/d175565ec09abdea35c038cd513da6ca
# Queue: https://gist.github.com/santosh/0c3f4d6c7d9382edaae7094048d71819
# Stack: https://gist.github.com/santosh/d7d75ea97bd03d09b32ce72af14f7ab8
from unittest import TestCase
from binarytree import Node, BinaryTree
class TestBinaryTree(TestCase):
"""
This class tests that your LinkedList class was implemented correctly.
All you have to do is run this file.
To do so, right click the file name in your PyCharm project and select the option
Run 'Unittests in tests'
If any tests fail, then you are not done yet.
If all tests pass, good job! You can move on to the next challenge.
"""
def test_node_creation(self):
name = "Jose"
value = 1
node = Node(name, value)
self.assertEqual(name, node.data)
self.assertEqual(value, node.value)
def test_tree_creation(self):
binary_tree = BinaryTree()
self.assertIsNone(binary_tree.get_root())
def test_add_to_tree(self):
name = "Jose"
value = 1
node = Node(name, value)
binary_tree = BinaryTree()
binary_tree.add(node)
self.assertEqual(binary_tree.get_root(), node)
def test_add_many_to_tree(self):
names = (("Jose", 2), ("Rolf", 1), ("Anna", 3))
nodes = [Node(name, value) for name, value in names]
binary_tree = BinaryTree()
for node in nodes:
binary_tree.add(node)
self.assertEqual(binary_tree.get_root(), nodes[0])
self.assertEqual(binary_tree.get_root().get_left(), nodes[1])
self.assertEqual(binary_tree.get_root().get_right(), nodes[2])
def test_find_in_tree(self):
names = (("Jose", 2), ("Rolf", 1), ("Anna", 3))
nodes = [Node(name, value) for name, value in names]
binary_tree = BinaryTree()
for node in nodes:
binary_tree.add(node)
for i in range(0, len(nodes)):
self.assertEqual(binary_tree.find(nodes[i].value), nodes[i])
def test_find_missing_in_list(self):
binary_tree = BinaryTree()
with self.assertRaises(LookupError):
binary_tree.find(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment