Construct Binary Tree from preorder and inorder traversal¶

The idea of the algorithm is to:¶

1) Take the first value of preorder as the current node value and delete it from the preorder list¶
2) Split the inorder list on the current node¶
3) Call itself on left split and then on right split¶
As the algorithm is called first on the left subtrees and then on the right subtrees, the preorder list will pop the element exactly at the time they are called (as list are pass by reference in functions)¶
In [ ]:
def buildTree(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
    def helper(preorder, inorder):
        if len(inorder) < 1:
            return(None)

        current_node = preorder.pop(0) # take current preorder value (preorder 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 preorder traversal first call left subtree and then right subtree
        left_subtree = helper(preorder, inorder[:current_node_idx])
        right_subtree = helper(preorder, inorder[current_node_idx+1:])
        
        return(TreeNode(current_node, left_subtree, right_subtree))

    return(helper(preorder, inorder))