#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <cctype> //判斷是不是數字、字母或、、node
using namespace std;ios
struct BinaryNode
{
char element;
BinaryNode *left;
BinaryNode *right;
};express
typedef BinaryNode * BinaryNodeptr;spa
void deleteAllNode(BinaryNodeptr ptr)
{
if (ptr->left!=NULL)
{
deleteAllNode(ptr->left);
}
else if (ptr->right!=NULL)
{
deleteAllNode(ptr->right);
}
else
{
delete ptr;
ptr = NULL;
}
}element
class expression_to_tree
{
public:
expression_to_tree(vector<char> str);
BinaryNodeptr createNewNode();
void printTree(BinaryNodeptr node);get
~expression_to_tree();input
BinaryNodeptr root;string
protected:
private:
vector<char> str;
};io
BinaryNodeptr expression_to_tree::createNewNode()
{
BinaryNodeptr node = new BinaryNode;
node->left = NULL;
node->right = NULL;class
return node;
}
expression_to_tree::expression_to_tree(vector<char> str)
{
stack<BinaryNodeptr> nodeStack; //保存除運算符以外的字符
BinaryNodeptr temp_node_ptr;
char c;
for (int i = 0; i < str.size(); i++)
{
cout << "輸入的字符爲:" << str[i] <<endl;
c = str[i];
temp_node_ptr = createNewNode();
//temp_node_ptr->element = c;
if (!(c == '+' || c == '-' || c == '*' || c == '/'))
{
cout << "推入棧的字符:" <<c<< endl;
temp_node_ptr->element = c;
nodeStack.push(temp_node_ptr);
}
else
{
cout << "推入棧的字符:" << c << endl;
root = createNewNode();
BinaryNodeptr leftNode ;
BinaryNodeptr rightNode ;
root->element = c;
rightNode = nodeStack.top();
nodeStack.pop();
leftNode = nodeStack.top();
nodeStack.pop();
root->left = leftNode;
root->right = rightNode;
nodeStack.push(root);
cout << "根結點:" << root->element << endl;
}
}
}
void expression_to_tree::printTree(BinaryNodeptr node)
{
if (node==NULL)
{
return;
}
else
{
printTree(node->left);
cout << node->element << endl;
printTree(node->right);
}
}
expression_to_tree::~expression_to_tree()
{
deleteAllNode(root);
}
int main(void)
{
vector<char> str;
char c;
BinaryNodeptr tree;
cout << "Please input expression:" << endl;
cout << "按q結束輸入:" << endl;
//輸入後綴表達式
c = getchar();
while (c!='q')
{
if (c == '+' || c == '-' || c == '*' || c == '/' || isalnum(c))
{
str.push_back(c);
getchar();
c = getchar();
}
else
{
cout << "請輸入字母、數字、或運算符" << endl;
return false;
}
}
expression_to_tree express(str);
tree = express.root;
express.printTree(tree); system("pause"); return 0; }