您的位置:首页 > 编程语言 > C语言/C++

C++实现简单的二叉树与二叉排序树

2018-03-15 09:35 447 查看
二叉树的实现#include<iostream>
using namespace std;
struct node{
node *left = NULL,*right = NULL;
char data;
};
node* insert(string str,int &x){
if(str[x] == '#'){
x++;
return NULL;
}else{
node *t = new node;
t->data = str[x];
x++;
t->left = insert(str,x);
t->right = insert(str,x);
return t;
}
}
void bl(node *root){
if(root != NULL){
bl(root->left);
cout<<root->data;
bl(root->right);
}
}
int main(){
string str;
node * root;
while(cin>>str){
int x = 0;
root = insert(str,x);
bl(root);
}
}二叉排序树的实现#include<iostream>
using namespace std;
struct node{
node *left = NULL,*right = NULL;
int data;
};
void insert(int x,node *&root){
if(root == NULL){
root = new node;
root->data = x;
}else{
if(root->data > x){
insert(x,root->left);
}else{
insert(x,root->right);
}
}
}
void bl(node *root){
if(root != NULL){
bl(root->left);
cout<<root->data;
bl(root->right);
}
}
int main(){
node *root = NULL;
int a[5] = {2,1,5,3,4};
for(int i = 0;i < 5;i++){
insert(a[i],root);
}
bl(root);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: