Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import Any, Callable
- class BinaryNode:
- value: Any
- left_child: 'BinaryNode'
- right_child: 'BinaryNode'
- def __init__(self, data=None):
- self.data = data
- self.left = None
- self.right = None
- def is_leaf(self):
- if self.left or self.right is not None:
- return False
- return True
- def add_left_child(self, data: Any):
- self.left = BinaryNode(data)
- def add_right_child(self, data: Any):
- self.right = BinaryNode(data)
- def traverse_pre_order(self, visit: Callable[[Any], None]):
- visit(self.data)
- if hasattr(self, 'left'):
- self.left.traverse_pre_order(visit)
- if hasattr(self, 'right'):
- self.right.traverse_pre_order(visit)
- # TODO: using print will display singular node value
- def search(self, value):
- def find(x):
- if x.data is not False:
- return True
- val2 = self.traverse_pre_order(find)
- if val2 is not True:
- return False
- else:
- return True
- class BinaryTree:
- root: BinaryNode
- def __init__(self, root):
- self.root = BinaryNode(root)
- def traverse_pre_order(self, visit: Callable[['Any'], None]):
- self.traverse_pre_order(visit)
- # TODO: using show will display the whole tree graphically or via text. Internal libraries allowed.
- test = BinaryTree(10)
- test.root.add_right_child(2)
- test.root.add_left_child(5)
- test.root.left.add_left_child(3)
- print(test.root.right.is_leaf())
- assert test.root.data == 10
- assert test.root.right.data == 2
- print(test.root.left.is_leaf())
- print(test.root.left.left.is_leaf())
- # print(test.root.search(3))
- # line which will not work
Advertisement
Add Comment
Please, Sign In to add comment