Question: Implement the following function: def create _ expression _ tree ( prefix _ exp _ str ) The function is given a string prefix _
Implement the following function:
def createexpressiontreeprefixexpstr
The function is given a string prefixexpstr which contains an arithmetic
expression in a prefix notation.
When called, it creates and returns a LinkedBinaryTree object, that is the
expression tree representing prefixexpstr
For example, the call: createexpressiontree
will create and return the following tree:
Note:
Assume that prefix expression will come in the following format:
All operators in the expression will be taken from the four basic arithmetic
operations and
All operands will be positive integers.
The tokens in the expression will be separated by a space.
Implementation requirements:
The nodes containing operators, should have the operator as a string, and
nodes containing numerals, should have the number as an int.
The runtime for creating the expression tree should be linear.
You are not allowed to use a stack in your implementation.
Hint: There is more than one way to solve this problem. One way is to start by
creating a list with the expressions tokens by using the split method and then
calling a helper function:
def createexpressiontreehelperprefixexp, startpos
This helper function would be recursive, and in order to efficiently pass the
subexpression that the call should consider, besides the list with the entire
expression, it also gets startpos, which is the index where the subexpression
starts we dont know how long the subexpression will be so we cant pass the
ending position too
The call to the helper function would return two values as a tuple: the first
would be the subtree it created that represent the subexpression starting at
startpos and the second would be the size of that subtree so you can know
where the next subexpression would start...
b Use the function you implemented in section a to implement the following
function:
def prefixtopostfixprefixexpstr
The function is given a string prefixexpstr which contains an arithmetic
expression in a prefix notation in the format described in section a
When called, it returns the string representation of the postfix equivalent of
prefixexpstr
For example, the call: prefixtopostfix will
return:
Implementation requirement: The runtime of this function should be linear.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
