The purpose of the exercise is to practice building and traversing an expression
ID: 3581357 • Letter: T
Question
The purpose of the exercise is to practice building and traversing an expression tree; so I want you to build a tree to hold the expression, and to evaluate the expression by traversing the tree. you have to build the expression tree, then traverse it to evaluate the expression. for each expression, you must produce - a graphical representation of the tree, - the numeric value of the expression. 2. Please use the following syntax for the arithmetic expressions that I want you to process: ::= | + | - ::= | * | / ::= | ( ) ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 You can make it slightly more complex by allowing greater integers than 9, but you can let your constants range from 0 to 9 only.
3. Make sure you understand how this syntax defines operator precedence and associativity rule. operator precedence: 3*5+4 is interpreted as (3*5)+4 rather than 3*(5+4)
. associativity rule: 3-5-4 is interpreted as 3-(5-4) rather than (3-5)-4.
Explanation / Answer
class expressionTree:
def __init__(self , value):
self.value = value
self.left = None
self.right = None
def checkOperator(op):
if (op == '+' or op == '-' or op == '*' or op == '/' or op == '^'):
return True
else:
return False
def inorderTraversal(node):
if node is not None:
inorderTraversal(node.left)
print node.value,
inorderTraversal(node.right)
def buildTree(expression):
stack = []
for char in expression:
if not checkOperator(char):
t = expressionTree(char)
stack.append(t)
else:
t = expressionTree(char)
t1 = stack.pop()
t2 = stack.pop()
t.right = t1
t.left = t2
stack.append(t)
t = stack.pop()
return t
expression = "4*(6+4)"
r = expressionTree(expression)
inorderTraversal(r)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.