Insert parens into a free-form SKI calculus expression Imagine a simple SKI calculus expression - for example, (((S α) β) γ). As you can see, each node of the rooted tree has exactly two children. Sometimes though, the parenthesis are omitted and the tree is unrooted (just to make the notation clear, I believe). The challenge is to put the parenthesis back, so that the tree is binary and rooted again.

The preferable way of I/O is mostly up to you; although the input and output has to at least look like the SKI calculus, and it obviously has to represent a tree.

The rule on adding parenthesis is simple: α β γ becomes ((α β) γ) (bind to the left), α β γ δ becomes (((α β) γ) δ), and so on.

You may assume that the input is a correct SKI-calculus expression.

If it wasn't clear enough, you may NOT add more braces than necessary. And if it helps you in any way, you can assume that the input contains no redundant parens (like, for example, (((SK)))).

Examples

S(KS)K =&gt; ((S(KS))K)
SS(SK) =&gt; ((SS)(SK))
Perl 5, 38 bytes



1while s/(\w|\((?1)*\)){2}(?!\))/($&amp;)/


Try it online!