एक एक्सप्रेशन ट्री मूल रूप से एक बाइनरी ट्री है जिसका उपयोग एक्सप्रेशन को दर्शाने के लिए किया जाता है। एक्सप्रेशन ट्री में, आंतरिक नोड्स ऑपरेटर्स से मेल खाते हैं और प्रत्येक लीफ नोड एक ऑपरेंड से मेल खाता है। यहाँ एक C++ प्रोग्राम है जो एक्सप्रेशन ट्री एल्गोरिदम को लागू करता है जो पोस्टफिक्स एक्सप्रेशन को इनपुट के रूप में लेता है और इनऑर्डर में पार किए गए संबंधित एक्सप्रेशन ट्री को उत्पन्न करता है।
एल्गोरिदम
शुरुआत
फ़ंक्शन construct_expression_tree():
फ्लैग = 1 जब यह ऑपरेंड हो।
फ्लैग = -1 जब यह ऑपरेटर हो।
S = suffix[0] यानी एक्सप्रेशन से पहला ऑपरेंड पढ़ें।
i = 0 से और जब तक s != 0 तक
जांचें कि सिंबल ऑपरेंड है या ऑपरेटर।
इनऑर्डर ट्रैवर्सल के लिए void inorder() फ़ंक्शन कॉल करें।
परिणाम प्रिंट करें।
i बढ़ाएं
समाप्ति।
उदाहरण कोड
#include <iostream> using namespace std; struct n//नोड घोषणा { char d; n *l; n *r; }; char pf[50]; int top = -1; n *a[50]; int r(char inputch)//जांचें कि सिंबल ऑपरेटर है या ऑपरेंड { if (inputch == '+' || inputch == '-' || inputch == '*' || inputch == '/') return (-1); else if (inputch >= 'A' || inputch <= 'Z') return (1); else if (inputch >= 'a' || inputch <= 'z') return (1); else return (-100); } void push(n *tree)//स्टैक में एलिमेंट्स पुश करें { top++; a[top] = tree; } n *pop() { top--; return (a[top + 1]); } void construct_expression_tree(char *suffix) { char s; n *newl, *p1, *p2; int flag; s = suffix[0]; for (int i = 1; s!= 0; i++) { flag = r(s); if (flag == 1) { newl = new n; newl->d = s; newl->l = NULL; newl->r = NULL; push(newl); } else { p1 = pop(); p2 = pop(); newl = new n; newl->d = s; newl->l = p2; newl->r = p1; push(newl); } s = suffix[i]; } } void inOrder(n *tree)//इनऑर्डर ट्रैवर्सल करें { if (tree != NULL) { inOrder(tree->l); cout << tree->d; inOrder(tree->r); } } int main(int argc, char **argv) { cout << "Enter Postfix Expression : "; cin >>pf; construct_expression_tree(pf); cout << "\nInfix Expression : "; inOrder(a[0]); return 0; }
आउटपुट
Enter Postfix Expression : 762*+6+ Infix Expression : 7+6*2+6