在 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
广告