object CalcTree(GenericTreeNode <Operation> root) { object[] args = new object[root.children.Count]; for (int i = 0; i < args.Length; i++) { args[i] = CalcTree(root.children[i]); } return(root.data.Calculate(args)); }
private static int SumAll(GenericTreeNode Node) { if (Node == null) { return(0); } int sum = Node.n; GenericTreeNode sib = Node.Silbling; while (sib != null) { sum += SumAll(sib); sib = sib.Silbling; } return(sum + SumAll(Node.Child)); }
public GenericTree() { Root = null; }
public GenericTreeNode(int n) { this.n = n; Silbling = null; Child = null; }
GenericTreeNode <Operation> CreateSyntaxTree(Queue <Token> input) { Stack <GenericTreeNode <Operation> > opStack = new Stack <GenericTreeNode <Operation> >(); GenericTreeNode <Operation> operation; while (input.Count > 0) { Token current = input.Dequeue(); switch (current.Type) { case TokenType.Value: operation = new GenericTreeNode <Operation>(); operation.data = new FloatValue(double.Parse(current.TokenText, CultureInfo.InvariantCulture)); opStack.Push(operation); break; case TokenType.Operation: operation = new GenericTreeNode <Operation>(); switch (current.TokenText) { case "+": operation.data = new FloatOperation2((a, b) => a + b); operation.children.Add(opStack.Pop()); operation.children.Add(opStack.Pop()); operation.children.Reverse(); break; case "-": operation.data = new FloatOperation2((a, b) => a - b); operation.children.Add(opStack.Pop()); operation.children.Add(opStack.Pop()); operation.children.Reverse(); break; case "*": operation.data = new FloatOperation2((a, b) => a * b); operation.children.Add(opStack.Pop()); operation.children.Add(opStack.Pop()); operation.children.Reverse(); break; case "/": operation.data = new FloatOperation2((a, b) => a / b); operation.children.Add(opStack.Pop()); operation.children.Add(opStack.Pop()); operation.children.Reverse(); break; default: throw new EvaluatorException(current.TokenStart, "Неизвестная операция: " + current.TokenText); } opStack.Push(operation); break; } } if (opStack.Count > 1) { throw new Exception(); } else if (opStack.Count == 1) { return(opStack.Pop()); } else { return(null); } }