Guest User

Binary Tree Test

a guest
Nov 6th, 2020
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. from typing import Any, Callable
  2.  
  3. class BinaryNode:
  4.     value: Any
  5.     left_child: 'BinaryNode'
  6.     right_child: 'BinaryNode'
  7.  
  8.     def __init__(self, data=None):
  9.         self.data = data
  10.         self.left = None
  11.         self.right = None
  12.  
  13.     def is_leaf(self):
  14.         if self.left or self.right is not None:
  15.             return False
  16.         return True
  17.  
  18.     def add_left_child(self, data: Any):
  19.         self.left = BinaryNode(data)
  20.  
  21.     def add_right_child(self, data: Any):
  22.         self.right = BinaryNode(data)
  23.  
  24.     def traverse_pre_order(self, visit: Callable[[Any], None]):
  25.         visit(self.data)
  26.         if hasattr(self, 'left'):
  27.             self.left.traverse_pre_order(visit)
  28.         if hasattr(self, 'right'):
  29.             self.right.traverse_pre_order(visit)
  30.  
  31.     # TODO: using print will display singular node value
  32.  
  33.     def search(self, value):
  34.         def find(x):
  35.             if x.data is not False:
  36.                 return True
  37.  
  38.         val2 = self.traverse_pre_order(find)
  39.         if val2 is not True:
  40.             return False
  41.         else:
  42.             return True
  43.  
  44. class BinaryTree:
  45.     root: BinaryNode
  46.  
  47.     def __init__(self, root):
  48.         self.root = BinaryNode(root)
  49.  
  50.     def traverse_pre_order(self, visit: Callable[['Any'], None]):
  51.         self.traverse_pre_order(visit)
  52.  
  53.     # TODO: using show will display the whole tree graphically or via text. Internal libraries allowed.
  54.  
  55.  
  56. test = BinaryTree(10)
  57.  
  58. test.root.add_right_child(2)
  59.  
  60. test.root.add_left_child(5)
  61.  
  62. test.root.left.add_left_child(3)
  63.  
  64. print(test.root.right.is_leaf())
  65.  
  66. assert test.root.data == 10
  67.  
  68. assert test.root.right.data == 2
  69.  
  70. print(test.root.left.is_leaf())
  71. print(test.root.left.left.is_leaf())
  72.  
  73. # print(test.root.search(3))
  74. # line which will not work
  75.  
Advertisement
Add Comment
Please, Sign In to add comment