Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views2 pages

Expression Tree

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Expression Tree

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Expression Tree

The expression tree is a binary tree in which each internal node


corresponds to the operator and each leaf node corresponds to the
operand so for example expression tree for 3 + ((5+9)*2) would be:

Construction of Expression Tree:


Now For constructing an expression tree we use a stack. We loop
through input expression and do the following for every character.
1. If a character is an operand push that into the stack
2. If a character is an operator pop two values from the stack
make them its child and push the current node again.
In the end, the only element of the stack will be the root of an
expression tree.
Code :

class Node:
def __init__(self, value=None, left=None, right=None,
next=None):
self.value = value
self.left = left
self.right = right
self.next = next

class Stack:
def __init__(self):
self.head = None

def push(self, node):


if not self.head:
self.head = node
else:
node.next = self.head
self.head = node

def pop(self):
if self.head:
popped = self.head
self.head = self.head.next
return popped
else:
raise Exception("Stack is empty")

class ExpressionTree:
def inorder(self, x):
if not x:
return
self.inorder(x.left)
print(x.value, end=" ")
self.inorder(x.right)

def main():
s = "ABC*+D/"
stack = Stack()
tree = ExpressionTree()
for c in s:
if c in "+-*/^":
z = Node(c)
x = stack.pop()
y = stack.pop()
z.left = y
z.right = x
stack.push(z)
else:
stack.push(Node(c))
print("The Inorder Traversal of Expression Tree: ", end="")
tree.inorder(stack.pop())

if __name__ == "__main__":
main()

You might also like