Convert Ternary Expression to a Binary Tree in C++


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.

Example

 Live Demo

#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;
}

Output

a b c d e

Updated on: 22-Jan-2020

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements