public double EvaluateTreeExpression(TreeChar expression) { //Base if (expression == null) { return(0); } //Induction int leaf = 0; if (Int32.TryParse(expression.val.ToString(), out leaf)) { return(leaf); } if (expression.val == '+') { return(EvaluateTreeExpression(expression.left) + EvaluateTreeExpression(expression.right)); } if (expression.val == '-') { return(EvaluateTreeExpression(expression.left) - EvaluateTreeExpression(expression.right)); } if (expression.val == '*') { return(EvaluateTreeExpression(expression.left) * EvaluateTreeExpression(expression.right)); } if (expression.val == '/') { return(EvaluateTreeExpression(expression.left) / EvaluateTreeExpression(expression.right)); } return(0); }
private TreeChar BuildTree(string preOrder, string inOrder, int indexPreOrder, int leftInOrder, int rightInOrder, Hashtable position) { //Base case if (String.IsNullOrEmpty(preOrder) || String.IsNullOrEmpty(inOrder) || indexPreOrder >= preOrder.Length || leftInOrder > rightInOrder) { return(null); } //Induction int indexInOrder = (int)position[preOrder[indexPreOrder]]; if (indexInOrder < leftInOrder || indexInOrder > rightInOrder) { return(BuildTree(preOrder, inOrder, indexPreOrder + 1, leftInOrder, rightInOrder, position)); } TreeChar tree = new TreeChar(preOrder[indexPreOrder]); tree.left = BuildTree(preOrder, inOrder, indexPreOrder + 1, leftInOrder, indexInOrder - 1, position); tree.right = BuildTree(preOrder, inOrder, indexPreOrder + 1, indexInOrder + 1, rightInOrder, position); return(tree); }
public TreeChar(char val) { this.val = val; this.left = null; this.right = null; }