//根据后缀表达式建立二叉树 #include <iostream> #include<stack> #include<string> using namespace std; class Note { public: char d; Note *Lchild; Note *Rchild; Note() { Lchild=NULL; Rchild=NULL; } }; stack<Note *> sta; string data; void make_tree(char a) { Note *t; if(a>='0'&&a<='9') { t=new Note; t->d=a; sta.push(t); } else { t=new Note; t->d=a; t->Rchild=sta.top(); sta.pop(); t->Lchild=sta.top(); sta.pop(); sta.push(t); } } bool print(char e) { cout<<e; return true; } bool print_tree(Note *head,bool (*visit)(char e)) { if(head) { if(visit(head->d)) if(print_tree(head->Lchild,print)) if(print_tree(head->Rchild,print)) return true; return false; } else return true; } bool delete_tree(Note *head) { if(head) { if(delete_tree(head->Lchild)) return true; else { delete head; return false; } if(delete_tree(head->Rchild)) return true; else { delete head; return false; } delete head; } return true; } int main() { cin>>data; Note *head; for(unsigned int i=0;i<data.length();i++) { make_tree(data[i]); } head=sta.top(); sta.pop(); print_tree(head,print); delete_tree(head); return 0; }