二叉排序树的建立

#include <cstdio>
#include <string>
#include <iostream>
using namespace std;

typedef struct node {
    char data;
    node *l;
    node *r;
}*Tree,node;

void insert(node *&p,char ch) {
    if(p==NULL) {
        p = new node;
        p->data = ch;
        p->l = NULL;
        p->r = NULL;
    } else {
        if(ch < p->data) {
            insert(p->l,ch);
        } else {
            insert(p->r,ch);
        }
    }
}

node *create(string s) {
    Tree tree = NULL;
    for(int i=0;i<s.size();i++) {
        insert(tree,s[i]);
    }
    return tree;
}

void LRD(node *t) {
    if(t->l != NULL) {
        LRD(t->l);
    }
    if(t->r != NULL) {
        LRD(t->r);
    }
    cout << t->data << " ";
}

int main(void) {
    string s0;
    cin >> s0;
    Tree tree = create(s0);
    LRD(tree);
    return 0;
} 

 

posted @ 2021-02-08 20:46  TheQ  阅读(39)  评论(0)    收藏  举报