My solution has both time and space complexity of O(n) I believe. The first pass is to create a tree, the second pass is to convert the tree to a string recursively. In fact, reconstructing a string uses multiple passes but their number is constant (reverse, map, join), and it's possible to rewrite the toStr function to use a single pass but the code won't be as concise. Reversion is only done at odd levels as at an even level it is reverted again back to original state.
Javascript
My solution has both time and space complexity of O(n) I believe. The first pass is to create a tree, the second pass is to convert the tree to a string recursively. In fact, reconstructing a string uses multiple passes but their number is constant (reverse, map, join), and it's possible to rewrite the
toStr
function to use a single pass but the code won't be as concise. Reversion is only done at odd levels as at an even level it is reverted again back to original state.