Construct Binary Tree from Inorder and Postorder Traversal in Python


Suppose we have the inorder and postorder traversal sequence of a binary tree. We have to generate the tree from these sequences. So if the postorder and inorder sequences are [9,15,7,20,3] and [9,3,15,20,7], then the tree will be −


Let us see the steps −

  • Suppose the method is called buildTree with preorder and inorder lists

  • root := last node from the postorder, and delete first node from postorder

  • root_index := index of root.val from the inorder list

  • left or root := buildTree(subset of inorder from root_index + 1 to end, postorder)

  • right or root := buildTree(subset of inorder from index 0 to root_index, postorder)

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def buildTree(self, preorder, inorder):
      """
      :type preorder: List[int]
      :type inorder: List[int]
      :rtype: TreeNode
      """
      if inorder:
      root = TreeNode(preorder.pop(0))
      root_index = inorder.index(root.val)
      root.left = self.buildTree(preorder,inorder[:root_index])
      root.right = self.buildTree(preorder,inorder[root_index+1:])
         return root

Input

[9,3,15,20,7]
[9,15,7,20,3]

Output

[3,9,20,null,null,15,7]
raja
Published on 03-Feb-2020 10:35:43
Advertisements