# Python program to construct full binary tree
# using its preorder traversal and preorder
# traversal of its mirror tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# A recursive function to construct a full binary tree
# from pre[] and preM[]. preIndex is used to keep
# track of index in pre[]. l is low index and h is high
# index for the current subarray in preM[].
def construct_binary_tree_util(pre, preM, preIndex, l, h, size):
if preIndex[0] >= size or l > h:
return None
# Create the root node using the
# current preIndex
root = Node(pre[preIndex[0]])
preIndex[0] += 1
# If the current subarray has only one
# element, no need to recurse
if l == h:
return root
# Search the next element of pre[] in preM[]
i = 0
for i in range(l, h + 1):
if pre[preIndex[0]] == preM[i]:
break
# Recursively construct left and right subtrees
if i <= h:
root.left = construct_binary_tree_util \
(pre, preM, preIndex, i, h, size)
root.right = construct_binary_tree_util(
pre, preM, preIndex, l + 1, i - 1, size)
return root
# Function to construct the full binary tree using
# its preorder traversal and preorder traversal of its mirror tree.
def construct_binary_tree(pre, preMirror):
preIndex = [0]
size = len(pre)
return construct_binary_tree_util(pre, preMirror, \
preIndex, 0, size - 1, size)
def print_inorder(curr):
if curr is None:
return
print_inorder(curr.left)
print(f"{curr.data} ", end="")
print_inorder(curr.right)
if __name__ == "__main__":
preOrder = [1, 2, 4, 5, 3, 6, 7]
preOrderMirror = [1, 3, 7, 6, 2, 5, 4]
root = construct_binary_tree(preOrder, preOrderMirror)
print_inorder(root)