Question : If the in-order and level order traversal of a tree are given, what is the minimum height of the tree
Example 1 :
input1 : {2,1,3}
input2 : {1,2,3}
input3 : 3
Output : 2
Example 2 :
input1 : {4,2,5,2,6,3,7}
input2 : {1,2,3,4,5,6,7}
input3 : 7
Output : 3
If you got this question in Campus round of Naggaro or on metti then it will a good solution for you
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def buildTree(level, ino):
if ino:
for i in range(0, len(level)):
if level[i] in ino:
node = Node(level[i])
io_index = ino.index(level[i])
break
if not ino:
return node
node.left = buildTree(level, ino[0:io_index])
node.right = buildTree(level, ino[io_index + 1:len(ino)])
return node
def height(root):
if root is None:
return 0
else:
return max(height(root.left),height(root.right))+1
#This is the function you have to write
def minHeight(input1,input2,input3):
global root
root = buildTree(input1, input2)
return height(root)
inorder = [4,2,5,1,6,3,7]
levelorder = [1,2,3,4,5,6,7]
print("height : ",minHeight(levelorder,inorder,len(inorder)))