# Python program to construct tree using
# inorder and levelorder traversals
class Node:
def __init__(self, x):
self.key = x
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 null
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)
l_cnt = index - s
r_cnt = e - index
# Level order array for left and right subtree.
l_level = []
r_level = []
# insert the left subtree elements
# into the set.
s_set = set(inorder[s:index])
# add the left and right elements to l_level and
# r_level
for i in range(1, e - s + 1):
# If the value is present in
# left subtree.
if level[i] in s_set:
l_level.append(level[i])
# else it will be present in
# right subtree.
else:
r_level.append(level[i])
# Recursively create the left and
# right subtree.
root.left = buildTreeRecur(inorder, l_level, s, index - 1)
root.right = buildTreeRecur(inorder, r_level, index + 1, e)
return root
# Main function
def buildTree(inorder, level, n):
# Build the tree recursively.
return buildTreeRecur(inorder, level, 0, n - 1)
def printInorder(root):
if root is None:
return
printInorder(root.left)
print(root.key, end=" ")
printInorder(root.right)
if __name__ == "__main__":
inorder = [4, 8, 10, 12, 14, 20, 22]
level = [20, 8, 22, 4, 12, 10, 14]
n = len(level)
root = buildTree(inorder, level, n)
printInorder(root)