Construct Binary Tree from inorder and postorder traversal¶

The idea of the algorithm is to:¶

1) Take the last value of postorder as the current node value and delete it from the postorder list¶
2) Split the inorder list on the current node¶
3) Call itself on right split and then on left split¶
As the algorithm is called first on the right subtrees and then on the left subtrees, the postorder list will pop the element exactly at the time they are called (as list are pass by reference in functions)¶
In [ ]:
def buildTree(inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        def helper(inorder, postorder):
            if len(inorder) < 1 :
                return None
            
            current_node = postorder.pop(-1)  # take current node as last element of postorder traversal (postorder is pass by reference and hence pop in one call will impact other calls)
            current_node_idx = inorder.index(current_node) # take the index to split inorder values for left and right subtrees 

            # With postorder traversal first call right subtree and then left subtree
            right_subtree = helper(inorder[ccurrent_node_idx+1:], postorder)
            left_subtree = helper(inorder[:ccurrent_node_idx], postorder)

            return(TreeNode(current_node, left_subtree, right_subtree))

        return(helper(inorder, postorder))