इस ट्यूटोरियल में, हम टर्नरी एक्सप्रेशन को बाइनरी ट्री में बदलने के लिए एक प्रोग्राम पर चर्चा करेंगे।
इसके लिए हमें एक त्रिगुट व्यंजक प्रदान किया जाएगा। हमारा काम विभिन्न रास्तों (विकल्पों) के आधार पर दिए गए एक्सप्रेशन को बाइनरी ट्री के रूप में बदलना है।
उदाहरण
#include<bits/stdc++.h>
using namespace std;
//node structure of tree
struct Node {
char data;
Node *left, *right;
};
//creation of new node
Node *newNode(char Data){
Node *new_node = new Node;
new_node->data = Data;
new_node->left = new_node->right = NULL;
return new_node;
}
//converting ternary expression into binary tree
Node *convertExpression(string str, int & i){
//storing current character
Node * root =newNode(str[i]);
//if last character, return base case
if(i==str.length()-1)
return root;
i++;
//if the next character is '?',
//then there will be subtree for the current node
if(str[i]=='?'){
//skipping the '?'
i++;
root->left = convertExpression(str,i);
//skipping the ':' character
i++;
root->right = convertExpression(str,i);
return root;
}
else return root;
}
//printing the binary tree
void display_tree( Node *root){
if (!root)
return ;
cout << root->data <<" ";
display_tree(root->left);
display_tree(root->right);
}
int main(){
string expression = "a?b?c:d:e";
int i=0;
Node *root = convertExpression(expression, i);
display_tree(root) ;
return 0;
} आउटपुट
a b c d e