Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python 3.8
- """
- Task: build a Binary Tree from a given array of integer in Python.
- Use the Pre, In, and Post Order iteration to print the values.
- Example of tree:
- 0
- 1 2
- 3 4 5 6
- """
- # • functions and classes start here •
- class Node:
- value = 0
- left = None
- right = None
- # tree building function
- def buildTree(a, indx):
- if indx < len(a):
- root = Node()
- root.value = a[indx]
- root.left = buildTree(a, 2*indx+1)
- root.right = buildTree(a, 2*indx+2)
- return root
- else:
- return None
- # pre-order function
- def preOrder(root):
- print(root.value)
- if root.left != None:
- preOrder(root.left)
- if root.right != None:
- preOrder(root.right)
- # in-order function
- def inOrder(root):
- if root.left != None:
- inOrder(root.left)
- print(root.value)
- if root.right != None:
- inOrder(root.right)
- # post function
- def postOrder(root):
- if root.left != None:
- postOrder(root.left)
- if root.right != None:
- postOrder(root.right)
- print(root.value)
- # • main starts from here •
- #array = raw_input().split()
- a = [0, 1, 2, 3, 4, 5, 6] # test array
- root = buildTree(a, 0)
- print("pre order:")
- preOrder(root) # output: 0, 1, 3, 4, 2, 5, 6
- print("\nin order:")
- inOrder(root) # output: 3, 1, 4, 0, 5, 2, 6
- print("\npost order:")
- postOrder(root) # output: 3, 4, 1, 5, 6, 2, 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement