Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Forming BST from user , using inorder and preorder transversals

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading