#include<iostream> #include<iomanip> #include<cstdlib> #include<queue> using namespace std; class Node { public: char data; Node *Left; Node *Right; }; class Tree : public Node { public: Node *root=new Node; string s; int a=0; int *pos=&a; Tree() // constructor { cout<<"enter string : "; getline(cin,s); } void tr() { MakeTree(s,pos,root); } void MakeTree(string expr, int *pos, Node *node) { if(expr[*pos] == '(') { (*pos)++; node->Left = new Node; node->Left->Left = NULL; node->Left->Right = NULL; MakeTree(expr,pos,node->Left); MakeTree(expr, pos, node); return; } if((expr[*pos] >= '0' && expr[*pos] <= '9') || (expr[*pos] >= 'a' && expr[*pos] <= 'z') || (expr[*pos] >= 'A' && expr[*pos] <= 'Z')) { node->data = expr[*pos]; (*pos)++; return; } if(expr[*pos] == '+' || expr[*pos] == '-' || expr[*pos] == '*' || expr[*pos] == '/') { node->data = expr[*pos]; (*pos)++; node->Right = new Node; node->Right->Left = NULL; node->Right->Right = NULL; MakeTree(expr, pos, node->Right); } if(expr[*pos] == ')') { (*pos)++; return; } } void pretrvsal() { prefix(root); } void prefix(Node *root) { if(root==NULL) { return ; } cout<<" "<<root->data<<" "; prefix(root->Left); prefix(root->Right); } void posttrvsal() { postfix(root); } void postfix(Node *root) { if(root==NULL) { return ; } postfix(root->Left); postfix(root->Right); cout<<" "<<root->data<<" "; return ; } void intrvsal() { infix(root); } void infix(Node *root) { if(root==NULL) { return ; } infix(root->Left); cout<<" "<<root->data<<" "; infix(root->Right); return ; } }; int main() { Tree t; t.tr(); cout<<"prefix : ";t.pretrvsal();cout<<endl; cout<<"postfix : ";t.posttrvsal(); cout<<endl; cout<<"infix : ";t.intrvsal();cout<<endl; return 0; }
Labels
Popular Posts
-
Binary Tree: A Tree in which each node has a degree of atmost 2. i.e. it can have either 0,1 or 2 children. Here, leaves a...
-
Recurrence relation : A recurrence relation is an equation that defines a sequence based on a rule that gives the next term as a funct...
-
BUBBLE SORT : Bubble sort is a simple sorting algorithm ...
Blog Archive
- March 2017 (1)
- March 2016 (1)
- October 2015 (1)
- September 2015 (1)
- August 2015 (5)
- July 2015 (2)
- June 2015 (4)
- January 2015 (4)
- December 2014 (5)
- November 2014 (1)
- October 2014 (1)
- September 2014 (3)
Powered by Blogger.