Construct a Binary Tree from Postorder and Inorder 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 −

  • Define a method build_tree(), this will take inorder, postorder −

  • If inorder list is not empty −

    • root := make a tree node with the last value of postorder, then delete that element

    • ind := index of root data in inorder list

    • right of root := build_tree(inorder from index ind to end, postorder)

    • left of root := build_tree(inorder from 0 to index ind - 1, postorder)

  • return root


Let us see the following implementation to get better understanding −

 Live Demo

class TreeNode:
   def __init__(self, data, left = None, right = None): = data
      self.left = left
      self.right = right
def print_tree(root):
   if root is not None:
      print(, end = ', ')
class Solution(object):
   def buildTree(self, inorder, postorder):
      if inorder:
         root = TreeNode(postorder.pop())
         ind = inorder.index(
         root.right = self.buildTree(inorder[ind+1:],postorder)
         root.left = self.buildTree(inorder[:ind],postorder)
         return root
ob1 = Solution()
print_tree(ob1.buildTree([9,3,15,20,7], [9,15,7,20,3]))