I am trying to build a binary search tree using following function:
I input a preorder and inorder list but in the final input I don’t get the desired tree.
Please help!
def buildTree(preorder, inorder):
if inorder:
root = Node(preorder.pop(0))
index = inorder.index(root.data)
root.l_child = buildTree(preorder,inorder[:index])
root.r_child = buildTree(preorder,inorder[index:])
return root
>Solution :
I think there is some indexing issues.Try this
def buildTree(preorder, inorder):
if inorder:
root = Node(preorder.pop(0))
index = inorder.index(root.data)
root.l_child = buildTree(preorder,inorder[:index])
root.r_child = buildTree(preorder,inorder[index+1:])
return root