1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
#pragma once
class BTree
{
private:
class Node
{
public:
Node *left, *right;
public:
Node() { left = right = NULL; }
double virtual Value() = 0;
static Node * Analize(const char *s, int i, int j)
{
int k;
int m, a, d;
for (k = i, m = a = -1; k < j; k++)
{
switch (s[k])
{
case '+':
case '-':
a = k;
break;
case '*':
case '/':
m = k;
break;
}
}
d = (a >= 0? a: m);
if (d >= 0) // Neu tim thay dau thi tra ve nut chua dau
{
SNode *snode = new SNode();
snode->sign = s[d];
snode->left = Node::Analize(s, i, d - 1);
snode->right = Node::Analize(s, d + 1, j);
return snode;
}
VNode *vnode = new VNode();
double v = 0.0;
double f = 10;
for (k = i; k < j; k++)
{
switch (s[k])
{
case '.':
f = 1;
break;
case ' ':
break;
default:
int d = s[k] - 48;
if (f > 1)
v = v * 10 + d;
else
v += d * (f /= 10);
}
}
vnode->val = v;
return vnode;
}
} *root;
class SNode : public Node
{
public:
char sign;
double Value()
{
double l = this->left->Value();
double r = this->right->Value();
switch (sign)
{
case '+': return l + r;
case '-': return l - r;
case '*': return l * r;
}
return l / r;
}
};
class VNode : public Node
{
public:
double val;
double Value()
{
return val;
}
};
private:
void RemoveNode(Node *node)
{
//
// insert the code here
//
}
//Function removeNode to delete a node
public:
BTree() : root(NULL) { }
~BTree()
{
this->RemoveNode(root);
}
public:
double operator()(const char * s)
{
int len = 0;
while (s[len]) len++;
this->RemoveNode(root);
this->root = Node::Analize(s, 0, len);
return root->Value();
}
};
|