写在前面:本博客为本人原创,严禁任何形式的转载!本博客只允许放在博客园(.cnblogs.com),如果您在其他网站看到这篇博文,请通过下面这个唯一的合法链接转到原文!
本博客全网唯一合法URL:https://www.cnblogs.com/acm-icpcer/p/10404776.html
按前序遍历次序构建二叉树:
#include<iostream> #include<cstring> #include<cstdio> #include<cstdlib> #include<fstream> using namespace std; struct tnode { char data; tnode *l,*r; }; class tree { public: tnode *root; tree() { //root=NULL; } tnode* getroot() { return this->root; } bool build(tnode * & root,char *input,int & index) { if(index>=strlen(input)) { return false; } if(input[index]=='#') { root=NULL; index++; } else { root=new tnode; root->data=input[index]; index++; build(root->l,input,index); build(root->r,input,index); } } bool pre_display(tnode *t,fstream &f); }; /* bool tree::build() { root->data='a'; root->l=new tnode(); root->l->data='c'; root->r=new tnode(); root->r->data='b'; return true; } */ /* bool tree::build(tnode * & root,char *input,int & index) { if(index>=strlen(input)) { return false; } if(input[index]=='#') { root=NULL; index++; } else { root=new tnode; root->data=input[index]; index++; build(root->l,input,index); build(root->r,input,index); } } */ bool tree::pre_display(tnode *t,fstream &f) { if(t!=NULL) { f<<t->data<<endl; cout<<t->data<<' '; pre_display(t->l,f); pre_display(t->r,f); } return true; } /* void preOrder(tnode * & root,char *input,int & index) { if(index>=strlen(input)) { return ; } if(input[index]=='#') { root=NULL; index++; } else { root=new tnode; root->data=input[index]; index++; preOrder(root->l,input,index); preOrder(root->r,input,index); } } */ //this function is not belongs to the tree class,writing for test purpose void inOrder(tnode * root) { if(root==NULL) { return ; } inOrder(root->l); cout<<root->data<<" "; inOrder(root->r); } int main() { fstream f("result.txt", ios::out); char buffer[256]; memset(buffer,'