flatten using tail recursion