daily pastebin goal
0%
SHARE
TWEET

Untitled

a guest Feb 11th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node(object):
  2.     def __init__(self, value):
  3.         self.value = value
  4.         self.left = None
  5.         self.right = None
  6.  
  7.  
  8. class BinaryTree(object):
  9.     def __init__(self, root):
  10.         self.root = Node(root)
  11.  
  12.     def print_tree(self, traversal_type):
  13.         if traversal_type == "preorder":
  14.             return self.preorder_print(tree.root, "")
  15.         elif traversal_type == "inorder":
  16.             return self.inorder_print(tree.root, "")
  17.         elif traversal_type == "postorder":
  18.             return self.postorder_print(tree.root, "")
  19.  
  20.         else:
  21.             print("Traversal type " + str(traversal_type) + " is not supported.")
  22.             return False
  23.  
  24.     def preorder_print(self, start, traversal):
  25.         """Root->Left->Right"""
  26.         if start:
  27.             traversal += (str(start.value) + "-")
  28.             traversal = self.preorder_print(start.left, traversal)
  29.             traversal = self.preorder_print(start.right, traversal)
  30.         return traversal
  31.  
  32.     def inorder_print(self, start, traversal):
  33.         """Left->Root->Right"""
  34.         if start:
  35.             traversal = self.inorder_print(start.left, traversal)
  36.             traversal += (str(start.value) + "-")
  37.             traversal = self.inorder_print(start.right, traversal)
  38.         return traversal
  39.  
  40.     def postorder_print(self, start, traversal):
  41.         """Left->Right->Root"""
  42.         if start:
  43.             traversal = self.postorder_print(start.left, traversal)
  44.             traversal = self.postorder_print(start.right, traversal)
  45.             traversal += (str(start.value) + "-")
  46.         return traversal
  47.  
  48. #              1
  49. #           /     \
  50. #          2       3
  51. #         / \     / \
  52. #        4   5   6   7
  53.  
  54. tree = BinaryTree(1)
  55. tree.root.left = Node(2)
  56. tree.root.right = Node(3)
  57. tree.root.left.left = Node(4)
  58. tree.root.left.right = Node(5)
  59. tree.root.right.left = Node(6)
  60. tree.root.right.right = Node(7)
  61.  
  62. print(tree.print_tree("preorder")) # 1-2-4-5-3-6-7
  63. print(tree.print_tree("inorder")) # 4-2-5-1-6-3-7
  64. print(tree.print_tree("postorder")) # 4-2-5-6-3-7-1
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top