Assignment 2
Assignment 2
AIM:
A. Construct an expression tree from a given postfix expression and perform non-recursive traversal
operations.
a. Build the expression tree using a stack data structure.
b. Perform non-recursive traversals: in-order, pre-order, and post-order.
Theory:
● Expression Tree: A binary tree used to represent expressions. In an expression tree, each
internal node corresponds to an operator and each leaf node corresponds to an operand
(constant or variable).
● Postfix Expression (Reverse Polish Notation): An expression where the operator follows the
operands. For example, the postfix expression AB+ corresponds to the infix expression A + B.
o For each operand, create a new tree node and push it onto a stack.
o For each operator, pop the top two nodes from the stack, create a new node with
the operator, and make the two nodes the left and right children of the new node.
Then push the new node back onto the stack.
o At the end of the expression, the stack will contain the root of the expression tree.
Terminologies:
Code:-
#include <iostream>
#include <stack>
#include <string>
struct Node
{
char data;
Node *left, *right;
};
curr = st.top();
st.pop();
cout << curr->data << " ";
curr = curr->right;
}
}
void preorder(Node * root)
{
if (root == nullptr)
return;
while (!st.empty())
{
Node *curr = st.top();
st.pop();
cout << curr->data
<< " ";
if (curr->right)
st.push(curr->right);
if (curr->left)
st.push(curr->left);
}
}
while (!s1.empty())
{
Node *curr = s1.top();
s1.pop();
s2.push(curr);
if (curr->left)
s1.push(curr->left);
if (curr->right)
s1.push(curr->right);
}
while (!s2.empty())
{
cout << s2.top()->data << " ";
s2.pop();
}
}
int main()
{
string postfix;
cout << "Enter postfix expression: ";
cin >> postfix;
Node *root = constructTree(postfix);
cout << "Inorder traversal of expression tree: ";
inorder(root);
cout << endl;
cout << "preorder traversal: ";
preorder(root);
cout << endl;
cout << "postorder traversal: ";
postorder(root);
cout << endl;
return 0;
}
Output: PS D:\cpp> cd "d:\cpp\.vscode\2nd Yr\" ; if ($?) { g++ DSA2.cpp -o DSA2 } ; if ($?) { .\DSA2 }
preorder traversal: - A + * b c d
postorder traversal: A b c * d + -
PS D:\cpp\.vscode\2nd Yr>
Case Studies:
1. Analyze the efficiency of building an expression tree from different postfix expressions.
3. Evaluate how the structure of the postfix expression affects the complexity of the
constructed expression tree.
Conclusion:
Constructing an expression tree from a postfix expression demonstrates the principles of tree data
structures and their application in expression evaluation. By implementing non-recursive traversal
techniques, this assignment highlights the flexibility of tree manipulations and provides insights into
efficient algorithms for expression handling in computational contexts. Understanding these
concepts is fundamental for further studies in data structures and algorithms.
4o mini