이 튜토리얼에서는 삼항 표현식을 이진 트리로 변환하는 프로그램에 대해 설명합니다.
이를 위해 삼항 표현식이 제공됩니다. 우리의 임무는 가능한 다양한 경로(선택 사항)에 따라 주어진 표현식을 이진 트리 형태로 변환하는 것입니다.
예시
#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