0% found this document useful (0 votes)
12 views

Expression Trees

Uploaded by

nvkeerthuvcet
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Expression Trees

Uploaded by

nvkeerthuvcet
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Expression Trees

What is Expression tree?


• Expression Tree is a binary tree in which the leaf nodes
are operands and the interior nodes are operators.
• Like binary tree, expression tree can also be traversed
by inorder, preorder and postorder traversal.
Constructing an Expression Tree
•Let us consider postfix expression given as an input
for constructing an expression tree by performing the
following steps :
1. Read one symbol at a time from the postfix
expression.
2. Check whether the symbol is an operand or operator.
(a) If the symbol is an operand, create a one - node
tree and push a pointer on to the stack.
(b) If the symbol is an operator pop two pointers from
the stack namely T1 and T2 and form a new tree with
root as the operator and T2 as a left child and T1 as a
right child. A pointer to this new tree is then pushed
onto the stack.
Example: ab + c *

• The first two symbols are operand, so create a one node tree and
push the pointer on to the stack.
ab + c *
• Next ‘+’ symbol is read, so two pointers are popped, a new tree is
formed and a pointer to this is pushed on to the stack.
ab + c *
• Next the operand C is read, so a one node tree is created and the
pointer to it is pushed onto the stack
ab + c *
•Now ‘*’ is read, so two trees are merged and the
pointer to the final tree is pushed onto the stack
Numeric Postfix expression
• Step 1: Construct the Expression Tree

• Process each element in the postfix expression:


• If the element is an operand (a number), create a node and push it
onto the stack.
• If the element is an operator, pop the last two nodes from the stack,
create a new node with the operator, and set the popped nodes as
the left and right children. Push this new node back onto the stack.
12 3 * 5 + 7 / - Postfix
12 3 * 5 + 7 / - Postfix
12 3 * 5 + 7 / - Postfix
12 3 * 5 + 7 / - Postfix
12 3 * 5 + 7 / - Postfix
12 3 * 5 + 7 / - Postfix
Find the prefix expression from
the constructed
12 tree
3 * 5 + 7 / - Pos
• Step 2: Convert the Expression Tree to Prefix Expression
• To convert the expression tree to a prefix expression, perform a
preorder traversal (Root, Left, Right).
12 3 * 5 + 7 / - Postfix

You might also like