Convert Ternary Expression to a Binary Tree | Class to define a node structure of the tree ; Function to convert ternary expression to a Binary tree It returns the root node of the tree ; Base case ; Create a new node object for the expression at ith index ; 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 [ 0 ] = = ':   ; Function to print the tree in a pre - order traversal pattern ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def convert_expression ( expression , i ) : NEW_LINE INDENT if i >= len ( expression ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = Node ( expression [ i ] ) NEW_LINE i += 1 NEW_LINE if ( i < len ( expression ) and expression [ i ] == " ? " ) : NEW_LINE INDENT root . left = convert_expression ( expression , i + 1 ) NEW_LINE DEDENT elif i < len ( expression ) : NEW_LINE INDENT root . right = convert_expression ( expression , i + 1 ) NEW_LINE DEDENT return root NEW_LINE DEDENT def print_tree ( root ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT print ( root . data , end = ' ▁ ' ) NEW_LINE print_tree ( root . left ) NEW_LINE print_tree ( root . right ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string_expression = " a ? b ? c : d : e " NEW_LINE root_node = convert_expression ( string_expression , 0 ) NEW_LINE print_tree ( root_node ) NEW_LINE DEDENT