# Python Program to construct tree using
# inorder and levelorder traversals
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to find the index of an element.
def searchValue(inorder, value, s, e):
for i in range(s, e + 1):
if inorder[i] == value:
return i
return -1
# Recursive function to build the binary tree.
def buildTreeRecur(inorder, level, s, e):
# For empty array, return None
if s > e:
return None
# create the root Node
root = Node(level[0])
# find the index of first element of level array
# in the in-order array.
index = searchValue(inorder, level[0], s, e)
# Level order array for left and right subtree.
lLevel = []
rLevel = []
# add the left and right elements to lLevel and rLevel
for i in range(1, e - s + 1):
j = searchValue(inorder, level[i], s, e)
if j < index:
lLevel.append(level[i])
else:
rLevel.append(level[i])
# Recursively create the left and right subtree.
root.left = buildTreeRecur(inorder, lLevel, s, index - 1)
root.right = buildTreeRecur(inorder, rLevel, index + 1, e)
return root
def buildTree(inorder, level, n):
return buildTreeRecur(inorder, level, 0, n - 1)
def printInorder(head):
if head is None:
return
printInorder(head.left)
print(head.key, end=" ")
printInorder(head.right)
if __name__ == "__main__":
inorder = [4, 8, 10, 12, 14, 20, 22]
level = [20, 8, 22, 4, 12, 10, 14]
n = len(inorder)
root = buildTree(inorder, level, n)
printInorder(root)