二叉树:树的度最大为2的树称为二叉树,二叉树的基本操作包括,先序,中序,后序和层次遍历,和求出树的高度等。
具体代码如下,建树树采用链表形式,另外也可以采用顺序存储结构。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct node{
char data;
node* l;
node* r;
node(){
l=r=NULL;
}
};
typedef node* Btree;
// 建树
void build(Btree& root){
char c;
cin>>c;
if(c=='0'){
root = NULL;
}
else{
root = new node();
root->data=c;
build(root->l);
build(root->r);
}
}
// 先序遍历
void pre_look(Btree& root){
if(root != NULL){
cout<<root->data;
pre_look(root->l);
pre_look(root->r);
}
}
// 中序遍历
void mid_look(Btree& root){
if(root != NULL){
mid_look(root->l);
cout<<root->data;
mid_look(root->r);
}
}
// 后序遍历
void end_look(Btree& root){
if(root != NULL){
end_look(root->l);
end_look(root->r);
cout<<root->data;
}
}
// 层次遍历
void Bfs_look(Btree& root){
if(root != NULL){
queue<node*> nodelist;
nodelist.push(root);
while(!nodelist.empty()){
node* n=nodelist.front();
nodelist.pop();
if(n!=NULL){
cout<<n->data;
nodelist.push(n->l);
nodelist.push(n->r);
}
}
}
}
//求出树的深度
int get_deep(Btree& root){
if(root == NULL)
return 0;
else{
int ld=get_deep(root->l);
int rd=get_deep(root->r);
return ld>rd?ld+1:rd+1;
}
}
int main()
{
Btree btree;
build(btree);
pre_look(btree);
cout<<endl;
mid_look(btree);
cout<<endl;
end_look(btree);
cout<<endl;
Bfs_look(btree);
cout<<endl;
cout<<get_deep(btree)<<endl;
return 0;
}
// AB0D00C00