Пример #1
0
        /// <summary>
        /// Constructs a new Expression Tree for a postfix Expression
        /// </summary>
        /// <param name="postfixParse">Postfix expression string</param>
        /// <returns>Root of the constructed tree</returns>
        private ExpressionTreeNode ConstructPostfixTree(List <string> postfixParse)
        {
            Stack <ExpressionTreeNode> treeStack = new Stack <ExpressionTreeNode>();

            for (int i = 0; i < postfixParse.Count; i++)
            {
                // If operator, pop twice and from stack and create new tree
                if (operatorFactory.IsValidOperator(postfixParse[i].ElementAt(0)))
                {
                    ExpressionTreeNode         newRight = treeStack.Pop();
                    ExpressionTreeNode         newLeft  = treeStack.Pop();
                    OperatorExpressionTreeNode newRoot  = operatorFactory.CreateOperatorNode(postfixParse[i].ElementAt(0));

                    newRoot.Right = newRight;
                    newRoot.Left  = newLeft;

                    treeStack.Push(newRoot);
                }
                else
                {
                    // Create a new variable or constant node and push to the stack
                    treeStack.Push(this.BuildSimpleNode(postfixParse[i]));
                }
            }

            if (treeStack.Count == 1)
            {
                return(treeStack.Pop());
            }
            else
            {
                // Throw exception?
                return(null);
            }
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExpressionTree"/> class.
 /// Parses and Expression string and builds the resulting tree
 /// </summary>
 /// <param name="expression">string expression</param>
 public ExpressionTree(string expression)
 {
     this.variables       = new Dictionary <string, double>();
     this.expressionParse = this.ConvertToPostfix(expression);
     this.root            = this.ConstructPostfixTree(expressionParse);
 }