/// <summary>
    /// Creates an ExpressionTree from infix notation (3 4 2 * 1 5 - 2 3 ^ ^ / +)
    /// </summary>
    private static ExpressionTree FromInfixToExpressionTree(List <Token> tokens)
    {
        Stack <ExpressionNode> expressionTree = new Stack <ExpressionNode>();

        for (int i = 0; i < tokens.Count; i++)
        {
            Token curr = tokens[i];

            if (curr is Number || curr is X || curr is Function)
            {
                // Simply add it to the stack
                expressionTree.Push(new ExpressionNode(curr));
            }
            else if (curr is Operator)
            {
                // We need to pop the top two nodes and make them the child of current operator
                var node = new ExpressionNode(curr);

                try {
                    node.ChildLeft  = expressionTree.Pop();
                    node.ChildRight = expressionTree.Pop();
                } catch (InvalidOperationException e) {
                    throw new InputException("No number for operator " + ((Operator)curr).Op, e, -1);
                }

                expressionTree.Push(node);
            }
        }

        var tree = new ExpressionTree();

        tree.BuildTree(expressionTree.Pop());

        return(tree);
    }
示例#2
0
        static void Main()
        {
            ExpressionTree exp         = new ExpressionTree();
            DataService    dataService = new DataService();
            Node           Tree        = exp.BuildTree(dataService.Expression); //or exp.BuildTree("your expression"), like exp.BuildTree("(1+2*3)")

            WriteLine("Expression is : " + dataService.Expression);
            Write("Preorder traversal (KLP) is : ");
            exp.PreOrder(Tree);
            Write("\nInorder traversal (LKP) is : ");
            exp.InOrder(Tree);
            Write("\nPostorder traversal (LPK) is : ");
            exp.PostOrder(Tree);
            WriteLine("\nThe result of the calculation is : " + exp.Calculate(Tree));
            WriteLine("Tree height is : " + exp.Height(Tree));
        }