包括了几个很基本的操作,树的创建删除遍历等等
#include<bits/stdc++.h>
using namespace std;
typedef struct node* tree_pointer;
struct node
{
char ch;
tree_pointer left_child,right_child;
};
tree_pointer create(tree_pointer T)
{
char ch;
cin>>ch;
if(ch=='.')
T=NULL;
else
{
T=new node;
T->ch=ch;
T->left_child=create(T->left_child);
T->right_child=create(T->right_child);
}
return T;
}
void destroy(tree_pointer T)
{
if(T)
{
destroy(T->left_child);
destroy(T->right_child);
delete T;
T=NULL;
}
}
void preorder(tree_pointer T)
{
if(T)
{
cout<<T->ch;
preorder(T->left_child);
preorder(T->right_child);
}
}
void inorder(tree_pointer T)
{
if(T)
{
inorder(T->left_child);
cout<<T->ch;
inorder(T->right_child);
}
}
void postorder(tree_pointer T)
{
if(T)
{
preorder(T->left_child);
preorder(T->right_child);
cout<<T->ch;
}
}
queue <tree_pointer> q;
void levelorder(tree_pointer T)
{
if(T)
{
q.push(T);
while(!q.empty())
{
tree_pointer temp;
temp=q.front();
q.pop();
cout<<temp->ch;
if(temp->left_child)
q.push(temp->left_child);
if(temp->right_child)
q.push(temp->right_child);
}
}
}
int leaf(tree_pointer T)
{
if(!T)
return 0;
else
{
if(!T->left_child&&!T->right_child)
return 1;
return leaf(T->left_child)+leaf(T->right_child);
}
}
int height(tree_pointer T)
{
if(!T)
return 0;
return 1+max(height(T->left_child),height(T->right_child));
}
void exchangechild(tree_pointer T)
{
if(T)
{
tree_pointer temp;
if(T->left_child||T->right_child)
{
temp=T->left_child;
T->left_child=T->right_child;
T->right_child=temp;
exchangechild(T->left_child);
exchangechild(T->right_child);
}
}
}
int main()
{
tree_pointer T;
T=create(T);
preorder(T);
cout<<endl;
inorder(T);
cout<<endl;
postorder(T);
cout<<endl;
levelorder(T);
cout<<endl;
return 0;
}