在 C++ 中將三元表示式轉換為二叉樹
在本教程中,我們將會探討一個將三元表示式轉換為二叉樹的程式。
為此,我們將會提供三元表示式。我們的任務是將給定表示式轉換成二叉樹形式,具體取決於各種可能的路徑(選擇)。
示例
#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
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP