Convert Ternary Expression to a Binary Tree

3.4

Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree.

Examples:

Input :  string expression =   a?b:c 
Output :        a
              /  \
             b    c

Input : expression =  a?b?c:d:e
Output :     a
           /  \
          b    e
        /  \
       c    d

Asked In : Facebook Interview

Idea is that we traverse a string make first character as root and do following step recursively .
1. If we see Symbol ‘?’
…….. then we add next character as the left child of root.
2. If we see Symbol ‘:’
…….. then we add it as the right child of current root.
do this process until we traverse all element of “String”.

Below c++ implementation of above idea

C++

// C++ program to covert a ternary expreesion to
// a tree.
#include<bits/stdc++.h>
using namespace std;

// tree structure
struct Node
{
    char data;
    Node *left, *right;
};

// function create a 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;
}

// Function to convert Ternary Expression to a Binary
// Tree. It return the root of tree
Node *convertExpression(string expression, int i)
{

    // Base case
    if (i >= expression.size())
        return NULL;

    // store current character of expression_string
    // [ 'a' to 'z']
    Node *root = newNode(expression[i]);

    // Move ahead in str
    ++i;

    // if current character of ternary expression is '?'
    // then we add next character as a left child of
    // current node
    if (i < expression.size() && expression.at(i)=='?')
        root->left = convertExpression(expression, i+1);

    // else we have to add it as a right child of
    // current node expression.at(0) == ':'
    else if (i < expression.size())
        root->right = convertExpression(expression, i+1);

    return root;
}

// function print tree
void printTree( Node *root)
{
    if (!root)
        return ;
    cout << root->data <<" ";
    printTree(root->left);
    printTree(root->right);
}

// Driver program to test above function
int main()
{
    string expression = "a?b?c:d:e";
    Node *root = convertExpression(expression, 0);
    printTree(root) ;
    return 0;
}

Java

// Java program to covert a ternary 
// expreesion to a tree.
import java.util.Queue;
import java.util.LinkedList;
 
// Class to represent Tree node 
class Node 
{
    char data;
    Node left, right;
 
    public Node(char item) 
    {
        data = item;
        left = null;
        right = null;
    }
}
 
// Class to covert a ternary expreesion to a Tree 
class BinaryTree 
{
    // Function to convert Ternary Expression to a Binary
    // Tree. It return the root of tree
    Node convertExpression(char[] expression, int i)
    {
        // Base case
        if (i >= expression.length)
            return null;
     
        // store current character of expression_string
        // [ 'a' to 'z']
        Node root = new Node(expression[i]);
     
        // Move ahead in str
        ++i;
     
        // if current character of ternary expression is '?'
        // then we add next character as a left child of
        // current node
        if (i < expression.length && expression[i]=='?')
            root.left = convertExpression(expression, i+1);
     
        // else we have to add it as a right child of
        // current node expression.at(0) == ':'
        else if (i < expression.length)
            root.right = convertExpression(expression, i+1);
     
        return root;
    }
    
    // function print tree
    public void printTree( Node root)
    {
        if (root == null)
            return;
                
        System.out.print(root.data +" ");
        printTree(root.left);
        printTree(root.right);
    }
    
// Driver program to test above function
    public static void main(String args[]) 
    {
        String exp = "a?b?c:d:e";
        BinaryTree tree = new BinaryTree();
        char[] expression=exp.toCharArray(); 
        Node root = tree.convertExpression(expression, 0);
        tree.printTree(root) ;
    }
}

/* This code is contributed by Mr. Somesh Awasthi */


Output :
a b c d e 

Time Complexity : O(n) [ here n is length of String ]

Asked in: Facebook

This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.4 Average Difficulty : 3.4/5.0
Based on 16 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.