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