-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpressionTree.py
47 lines (41 loc) · 1.22 KB
/
ExpressionTree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class ExpressionTree:
root = Node()
currentNode = root
st = Stack()
def __init__(self, x[]): #string array input is given, with each token in each index
for (i in x)
{
self.st.push(Node(i))
}
processStack(root)
def add(parent, newNode):
parent.addChild(newNode)
def addOperator(parent, operator):
add(parent, newNode)
def addOperand(parent, operand):
add(parent, operand)
def processStack(current):
{
if(!st.isEmpty())
{
if(st.peek().isAnOperator())
{
temp = st.peek()
addOperator(currentNode, st.pop())
currentNode = temp
}
else #it's an operand
{
if(currentNode.operandCount < 2)
{
addOperand(currentNode, st.pop())
currentNode.operandCount++
}
else #parent has two operands already
{
currentNode = currentNode.parent
processStack(currentNode) #continue processing stack in the parent node
}
}
}
}