CJCoding With Joseph
15free / daySign inCreate account

unique_ptr Expression Tree from Postfix

Build an expression tree from a postfix expression in which EVERY node is owned by a std::unique_ptr. Write no new and no delete of your own anywhere in this program.

Input (stdin): one postfix expression, tokens separated by whitespace — each a non-negative integer or one of +, -, *. Read tokens until the input runs out.

Use the classic stack method: a number becomes a leaf; an operator pops the top two subtrees (the FIRST one popped is the RIGHT operand) and becomes a node with those two children. When the input ends, the one tree left on the stack is the root.

Then print exactly two lines. For the input 2 3 + 4 * the output is exactly what is shown in Expected Output.

Line 1 is Infix:  followed by the fully parenthesized infix form: a leaf prints just its number; an operator node prints (, the left side, a space, the operator, a space, the right side, then ). Line 2 is Value:  followed by the integer the expression evaluates to.

This question checks for memory leaks. Include <memory>.

Write everything yourself, including main.

Expected Output:

Infix: ((2 + 3) * 4)
Value: 20

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Pointers
📥 Auto-Input:
2 3 + 4 *\n
This input is automatically fed to your program's stdin
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.