Esempio n. 1
0
        public void inorder(TreeNode node)
        {
            if (node == null)
                return;

            inorder(node.left);
            Console.Write(" {0} ", node.toString());
            inorder(node.right);
        }
Esempio n. 2
0
        private TreeNode build(string[] tokens, ref int start)
        {
            if(start >= tokens.Length)
                return null;

            bool leaf;
            double val;
            TreeNode node = null;

            leaf = double.TryParse(tokens[start], out val);
            if(leaf)
            {
                node = new TreeNode(leaf, '\0', val);
                start++;
            }
            else
            {
                node = new TreeNode(leaf, char.Parse(tokens[start]), 0.0);
                start++;
                node.left = build(tokens, ref start);
                node.right = build(tokens, ref start);
            }
            return node;
        }
Esempio n. 3
0
        private double Evaluate(TreeNode node)
        {
            double result = 0.0;
            if (node.isleaf)
                result = node.val;
            else
            {
                char op = node.op;
                double left, right;

                left = Evaluate(node.left);
                right = Evaluate(node.right);

                switch (op)
                {
                    case '+': result = left + right;
                        break;
                    case '*': result = left * right;
                        break;
                    case '-': result = left - right;
                        break;
                    case '/':
                        if (right != 0)
                            result = left / right;
                        else
                            throw new Exception("division by zero");
                        break;
                    default: Console.WriteLine("unrecognized character: " + op);
                        break;
                }
            }
            return result;
        }
Esempio n. 4
0
 public void ExpressionTree(string prefixNot)
 {
     string[] tokens = prefixNot.Split(' ');
     int start = 0;
     root = build(tokens, ref start);
 }