
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) in C++
- Convert a Binary Tree into its Mirror Tree in C++
- Ternary Expression Parser in C++
- Program to evaluate ternary expression in C++
- Convert Sorted List to Binary Search Tree in C++
- Convert Sorted Array to Binary Search Tree in Python
- Convert a Binary Tree to a Circular Doubly Link List in C++
- C++ Program to Implement Ternary Tree
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property in C++
- Convert a given Binary tree to a tree that holds Logical AND property on C++
- Program to convert a linked list into a binary search tree in C++
- Program to convert binary search tree to a singly linked list in C++?
- Python program to convert a given binary tree to doubly linked list
- Convert a given Binary Tree to Doubly Linked List (Set 1) in C++
- Convert a given Binary Tree to Doubly Linked List (Set 2) in C++

Advertisements