c++二叉排序樹+中序遍曆

來源:互聯網
上載者:User
/* cpp 二叉排序樹   儘管二叉排序樹很簡單,但是第一次寫二叉排序樹的類,還是有一點的麻煩。   不知道如何寫遞迴,如何寫成員函數等。。。   第一次總是會很糾結的,所以發篇博文來紀念下自己寫的第一個C++類    BY Mr_Zys*/#include<iostream>#include<Cstring>#define MAXN 10000using namespace std;typedef struct Node{    char data[MAXN];    Node *l;    Node *r;}   Node,*pointNode;class BTree{     public:           BTree();           //void Creat();           void Insert(char *s);           void Query();           void Query(pointNode r);           pointNode Getroot();           ~BTree();     private:           pointNode root;};BTree::BTree(){     root=NULL;}void BTree::Insert(char *s){     if(root==NULL){       root=new Node;       strcpy(root->data,s);       root->l=NULL;       root->r=NULL;       return;     }     pointNode T=root,P;     while(T!=NULL){       if(strcmp(T->data,s)==0){          cout<<"REERO: Data has existed;"<<endl;          return;       }       P=T;       T=strcmp(T->data,s)>0?T->l:T->r;     }     T=new Node;     strcpy(T->data,s);     T->l=NULL;     T->r=NULL;     if(strcmp(P->data,s)>0) P->l=T;     if(strcmp(P->data,s)<0) P->r=T;     cout<<"Now is the root's data:"<<root->data<<endl;}pointNode BTree::Getroot(){     return root;}void BTree::Query(pointNode r){    if(r!=NULL){        Query(r->l);        cout<<r->data<<endl;        Query(r->r);    }}void BTree::Query(){    pointNode r;    r=Getroot();    Query(r);}BTree::~BTree(){}int main(){    BTree tree;    char s[MAXN];    while(1){        cout<<"Please Input The Information: ";        cin>>s;        if(s[0]=='#') break;        tree.Insert(s);    }    tree.Query();    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.