Advertisement
AlimusSifar

Binary Tree and Pre-In-Post order Iteration | Python 3.8

May 14th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. # Python 3.8
  2. """
  3. Task: build a Binary Tree from a given array of integer in Python.
  4. Use the Pre, In, and Post Order iteration to print the values.
  5.  
  6. Example of tree:
  7.     0
  8.   1   2
  9.  3 4 5 6
  10. """
  11.  
  12. # • functions and classes start here •
  13. class Node:
  14.     value = 0
  15.     left = None
  16.     right = None
  17.  
  18. # tree building function
  19. def buildTree(a, indx):
  20.     if indx < len(a):
  21.         root = Node()
  22.         root.value = a[indx]
  23.         root.left = buildTree(a, 2*indx+1)
  24.         root.right = buildTree(a, 2*indx+2)
  25.         return root
  26.     else:
  27.         return None
  28.  
  29. # pre-order function
  30. def preOrder(root):
  31.     print(root.value)
  32.    
  33.     if root.left != None:
  34.         preOrder(root.left)
  35.    
  36.     if root.right != None:
  37.         preOrder(root.right)
  38.  
  39. # in-order function
  40. def inOrder(root):
  41.     if root.left != None:
  42.         inOrder(root.left)
  43.    
  44.     print(root.value)
  45.    
  46.     if root.right != None:
  47.         inOrder(root.right)
  48.  
  49. # post function
  50. def postOrder(root):
  51.     if root.left != None:
  52.         postOrder(root.left)
  53.    
  54.     if root.right != None:
  55.         postOrder(root.right)
  56.    
  57.     print(root.value)
  58.    
  59. # • main starts from here •
  60. #array = raw_input().split()
  61. a = [0, 1, 2, 3, 4, 5, 6] # test array
  62. root = buildTree(a, 0)
  63.  
  64. print("pre order:")
  65. preOrder(root) # output: 0, 1, 3, 4, 2, 5, 6
  66.  
  67. print("\nin order:")
  68. inOrder(root) # output: 3, 1, 4, 0, 5, 2, 6
  69.  
  70. print("\npost order:")
  71. postOrder(root) # output: 3, 4, 1, 5, 6, 2, 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement