8
In informatics, we often use trees in lots of different forms and representations. The three major methods of serialising binary trees are prefix, infix and postfix notation. For example, the following binary tree:
(source: Dutch Olympiad in Informatics, finals, 2012/13)
can be represented in prefix notation as abrxdbe
, in infix as rbxabde
and in postfix as rxbbeda
.
In this case, you are confronted with a complete binary tree represented in infix notation. Your task is to convert this tree to prefix notation. Your input on stdin will be 2n-1 lowercase alphabet characters, a-z and no more, ended with a newline character, for any integer n such that 1 ≤ n ≤ 16. Thus, the maximum number of characters you will get is 65535. Output the tree to stdout in the same way, but then in prefix format.
This is code golf, so the shortest code, counted in bytes, will win. Votes will act as a tie breaker, and if those tie up as well, submission date and time.
possible duplicate of Convert from Infix Notation to Prefix Notation
– Peter Taylor – 2014-04-25T11:11:44.553@PeterTaylor Thanks for mentioning, but I think this challenge is actually different because you don't need to evaluate an entire expression, just a simple 2<sup>n</sup>-1 binary tree. – tomsmeding – 2014-04-25T11:14:13.720
Ok, the restriction to complete binary trees does simplify things quite a lot. – Peter Taylor – 2014-04-25T11:50:43.617