Expression Tree | C # program to construct an expression tree ; An expression tree node ; A utility function to check if ' c ' is an operator ; Utility function to do inorder traversal ; Returns root of constructed tree for given postfix expression ; Traverse through every character of input expression ; If operand , simply Push into stack ; operator ; Pop two top nodes Store top Remove top ; make them children ; System . out . println ( t1 + " " + t2 ) ; Add this subexpression to stack ; only element will be root of expression tree ; Driver code
using System ; using System . Collections ; public class Node { public char value ; public Node left , right ; public Node ( char item ) { value = item ; left = right = null ; } } class ExpressionTree { Boolean isOperator ( char c ) { if ( c == ' + ' c == ' - ' c == ' * ' c == ' / ' c == ' ^ ' ) { return true ; } return false ; } void inorder ( Node t ) { if ( t != null ) { inorder ( t . left ) ; Console . Write ( t . value + " ▁ " ) ; inorder ( t . right ) ; } } Node constructTree ( char [ ] postfix ) { Stack st = new Stack ( ) ; Node t , t1 , t2 ; for ( int i = 0 ; i < postfix . Length ; i ++ ) { if ( ! isOperator ( postfix [ i ] ) ) { t = new Node ( postfix [ i ] ) ; st . Push ( t ) ; } else { t = new Node ( postfix [ i ] ) ; t1 = ( Node ) st . Pop ( ) ; t2 = ( Node ) st . Pop ( ) ; t . right = t1 ; t . left = t2 ; st . Push ( t ) ; } } t = ( Node ) st . Peek ( ) ; st . Pop ( ) ; return t ; } public static void Main ( String [ ] args ) { ExpressionTree et = new ExpressionTree ( ) ; String postfix = " ab + ef * g * - " ; char [ ] charArray = postfix . ToCharArray ( ) ; Node root = et . constructTree ( charArray ) ; Console . WriteLine ( " infix ▁ expression ▁ is " ) ; et . inorder ( root ) ; } }