Added BFS encode and expand helper method.