pr-4 Expression tree
pr-4 Expression tree
Roll No : S511073
Division : A
Subject : DSA
Problem Statement : To construct an Expression Tree from postfix and prefix expression. Perform
recursive and non- recursive in-order, pre-order and post-order traversals.
#include <iostream>
#include <stack>
#include <string>
struct Node
char value;
Node* left;
Node* right;
};
stack<Node*> st;
if (isalnum(ch))
st.push(new Node(ch));
else
node->left = left;
node->right = right;
st.push(node);
return st.top();
stack<Node*> st;
char ch = prefix[i];
if (isalnum(ch))
st.push(new Node(ch));
else
node->left = left;
node->right = right;
st.push(node);
return st.top();
}
if (node)
inorderRecursive(node->left);
inorderRecursive(node->right);
stack<Node*> st;
while (current) {
st.push(current);
current = current->left;
current = current->right;
if (node)
{
preorderRecursive(node->left);
preorderRecursive(node->right);
if (!root) return;
stack<Node*> st;
st.push(root);
while (!st.empty())
if (current->right) st.push(current->right);
if (current->left) st.push(current->left);
if (node)
postorderRecursive(node->left);
postorderRecursive(node->right);
}
void postorderNonRecursive(Node* root)
if (!root) return;
stack1.push(root);
while (!stack1.empty())
stack2.push(current);
if (current->left) stack1.push(current->left);
if (current->right) stack1.push(current->right);
while (!stack2.empty())
stack2.pop();
int main()
inorderRecursive(postfixTree);
preorderRecursive(postfixTree);
preorderNonRecursive(postfixTree);
postorderRecursive(postfixTree);
postorderNonRecursive(postfixTree);
inorderRecursive(prefixTree);
inorderNonRecursive(prefixTree);
preorderRecursive(prefixTree);
preorderNonRecursive(prefixTree);
postorderRecursive(prefixTree);
postorderNonRecursive(prefixTree);
return 0;
}
Output :