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
Example
Let us see the following implementation to get better understanding −
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) class Solution(object): def buildTree(self, inorder, postorder): if inorder: root = TreeNode(postorder.pop()) ind = inorder.index(root.data) 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]))
Input
[9,3,15,20,7] [9,15,7,20,3]
Output
[9,3,15,20,7]