-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prac5-B7.cpp
95 lines (77 loc) · 2.01 KB
/
Prac5-B7.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Construct an expression tree from the given prefix expression eg. +--a*bc/def and traverse it using post-order traversal (non recursive) and then delete the entire tree. */
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode
{
char data;
TreeNode *left;
TreeNode *right;
TreeNode(char val) : data(val), left(nullptr), right(nullptr) {}
};
bool isOperand(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
TreeNode *constructExpressionTree(const string &prefix)
{
stack<TreeNode *> stk;
for (int i = prefix.length() - 1; i >= 0; --i)
{
char c = prefix[i];
if (isOperand(c))
{
stk.push(new TreeNode(c));
}
else
{
TreeNode *newNode = new TreeNode(c);
newNode->left = stk.top();
stk.pop();
newNode->right = stk.top();
stk.pop();
stk.push(newNode);
}
}
return stk.top();
}
void postOrderTraversalAndDelete(TreeNode *root)
{
stack<TreeNode *> stk;
TreeNode *current = root;
TreeNode *lastVisited = nullptr;
while (current || !stk.empty())
{
if (current)
{
stk.push(current);
current = current->left;
}
else
{
TreeNode *topNode = stk.top();
if (topNode->right && lastVisited != topNode->right)
{
current = topNode->right;
}
else
{
cout << topNode->data << " ";
lastVisited = topNode;
stk.pop();
delete topNode;
}
}
}
}
int main()
{
cout<<"Prepared By - Anshul Singh"<<endl;
cout<<"DSAL Practical 05 (B-7)"<<endl;
string prefixExpression ;
cout<<"Enter the Prefix Expression"<<endl;
cin>>prefixExpression;
TreeNode *root = constructExpressionTree(prefixExpression);
postOrderTraversalAndDelete(root);
return 0;
}