from collections import deque # Node Structure class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to find the index of an element in the array def search(inorder, value, left, right): for i in range(left, right + 1): if inorder[i] == value: return i return -1 # Recursive function to build the binary tree. def buildTreeRecur(inorder, preorder, preIndex, left, right): # For empty inorder array, return null if left > right: return None rootVal = preorder[preIndex[0]] preIndex[0] += 1 root = Node(rootVal) index = search(inorder, rootVal, left, right) # Recursively create the left and right subtree. root.left = buildTreeRecur(inorder, preorder, preIndex, left, index - 1) root.right = buildTreeRecur(inorder, preorder, preIndex, index + 1, right) return root # Function to construct tree from its inorder and preorder traversals def buildTree(inorder, preorder): preIndex = [0] return buildTreeRecur(inorder, preorder, preIndex, 0, len(preorder) - 1) def getHeight(root, h): if root is None: return h - 1 return max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)) def levelOrder(root): queue = deque([[root, 0]]) lastLevel = 0 # function to get the height of tree height = getHeight(root, 0) # printing the level order of tree while queue: node, lvl = queue.popleft() if lvl > lastLevel: print() lastLevel = lvl # all levels are printed if lvl > height: break # printing null node print("N" if node.data == -1 else node.data, end=" ") # null node has no children if node.data == -1: continue if node.left is None: queue.append([Node(-1), lvl + 1]) else: queue.append([node.left, lvl + 1]) if node.right is None: queue.append([Node(-1), lvl + 1]) else: queue.append([node.right, lvl + 1]) if __name__ == "__main__": inorder = [3, 1, 4, 0, 5, 2] preorder = [0, 1, 3, 4, 2, 5] root = buildTree(inorder, preorder) levelOrder(root)