Professional Documents
Culture Documents
Name of Student:
Marks: Sign:
THEORY:
An expression tree in data structure used to represent an expression in the form of a tree. After
generating the expression tree of an expression, we can perform inorder traversal to generate infix
expressions. Similarly, doing a postorder traversal of the expression tree will generate postfix
expressions.
In this, we are going to discuss the expression tree in data structure and how we can generate an
expression tree from a given expression using stacks.
Expression trees are used to express a mathematical expression in the form of a binary tree.
Expression trees are binary trees in which each internal (non-leaf) node is an operator and each
leaf node is an operand.
1. Let exprTree be the input expression tree.
2. Create a recursive function dfsTree(Node* node) to perform the dfs of the expression tree.
Here Node represents individual nodes of the tree.
3. If node is null or node represents an operand, return node’s value.
4. Otherwise, perform dfsTree(node->left) and dfsTree(node->right) and store them in L1 and
L2.
5. Finally, perform the operation represented by node->value between L1 and L2.
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.
First, let us discuss how to evaluate a given expression tree in data structure. For example, if we
have an expression A * B + C / D. Then, the expression tree would be like the figure shown below:
struct node
{
struct node *right,*left,*prev;
char data;
}*cur,*par,*root=NULL;
if(root == NULL)
{
root = new_node;
cur = par = root;
}
else
{
if(a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/')
{
if(par -> right == NULL)
{
cur = new_node;
par -> right = cur;
}
else if(par -> left == NULL)
{
cur = new_node;
par -> left = cur;
cur -> prev = par;
par = cur;
}
else
{
while(par -> left != NULL)
{
par = par -> prev;
}
cur = new_node;
par -> left = cur;
cur -> prev = par;
par = cur;
}
}
else
{
if(par -> right == NULL)
{
cur = new_node;
par -> right = cur;
cur -> prev = par;
}
else if(par -> left == NULL)
{
cur = new_node;
par -> left = cur;
cur -> prev = par;
}
else
{
while(par -> left != NULL)
{
par = par -> prev;
}
cur = new_node;
par -> left = cur;
cur -> prev = par;
}
}
}
}