← Back to Pointers
Question 718
unique_ptr Expression Tree from Postfix
unique_ptr Expression Tree from Postfix
Build an expression tree from a postfix expression in which EVERY node is owned by astd::unique_ptr. Write nonewand nodeleteof 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 input2 3 + 4 *the output is exactly what is shown in Expected Output. Line 1 isInfix: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 isValue:followed by the integer the expression evaluates to. This question checks for memory leaks. Include<memory>. Write everything yourself, includingmain.
Expected Output:
Infix: ((2 + 3) * 4) Value: 20
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Pointers
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.