二叉排序树的建立

#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;
} 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容