|
| 1 | +class Node: |
| 2 | + """Base class to contain the tree metadata per instance of the class""" |
| 3 | + |
| 4 | + def __init__(self, val): |
| 5 | + self.l_child = None |
| 6 | + self.r_child = None |
| 7 | + self.data = val |
| 8 | + |
| 9 | + |
| 10 | +def binary_insert(root, node): |
| 11 | + """This recursive function will insert the objects into the tree""" |
| 12 | + if root is None: # If we don't have a root node |
| 13 | + root = node # Set the root node equal to the first node argument that was provided |
| 14 | + else: # We already have a root |
| 15 | + if root.data > node.data: # If our current root is bigger than the node we are about to insert |
| 16 | + if root.l_child is None: # If we don't have any node to the left of root |
| 17 | + root.l_child = node # Insert the node as the left node under root |
| 18 | + else: # There's already a node to the left of root |
| 19 | + binary_insert( |
| 20 | + root.l_child, node |
| 21 | + ) # Call the insert function recursively with the left node value as the |
| 22 | + # temp root for comparison |
| 23 | + else: # Node to be inserted is bigger than root (going right side) |
| 24 | + if root.r_child is None: # if there's no right child |
| 25 | + root.r_child = node # insert the node as the right child of root (under) |
| 26 | + else: # |
| 27 | + binary_insert( |
| 28 | + root.r_child, node |
| 29 | + ) # Call the insert function recursively with the right node value as the |
| 30 | + # temp root for comparison |
| 31 | + |
| 32 | + |
| 33 | +def post_sort_print(root): |
| 34 | + if not root: |
| 35 | + return None |
| 36 | + post_sort_print(root.l_child) |
| 37 | + print(root.data) |
| 38 | + post_sort_print(root.r_child) |
| 39 | + |
| 40 | + |
| 41 | +def pre_sort_print(root): |
| 42 | + if not root: |
| 43 | + return None |
| 44 | + print(root.data) |
| 45 | + pre_sort_print(root.l_child) |
| 46 | + pre_sort_print(root.r_child) |
| 47 | + |
| 48 | + |
| 49 | +r = Node(6) |
| 50 | +binary_insert(r, Node(2)) |
| 51 | +binary_insert(r, Node(8)) |
| 52 | +binary_insert(r, Node(90)) |
| 53 | +binary_insert(r, Node(23)) |
| 54 | +binary_insert(r, Node(12)) |
| 55 | +binary_insert(r, Node(91)) |
| 56 | + |
| 57 | +print("---------") |
| 58 | +print("PRE SORT") |
| 59 | +pre_sort_print(r) |
| 60 | +print("---------") |
| 61 | +print("POST SORT") |
| 62 | +post_sort_print(r) |
0 commit comments