Convert Ternary Expression to a Binary Tree in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert ternary expression to a binary tree.

For this we will be provided with a ternary expression. Our task is to convert the given expression in the form of a binary tree depending upon the various paths(choices) possible.


 Live Demo

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
      return root;
   //if the next character is '?',
   //then there will be subtree for the current node
      //skipping the '?'
      root->left = convertExpression(str,i);
      //skipping the ':' character
      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 <<" ";
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
Published on 22-Jan-2020 11:50:11