#include <iostream>
#include <stack>
#include <vector>
#include "algorithm"
#include "queue"
using namespace std;
template<class T>struct binode
{
T data;
binode<T>*leftchild;
binode<T>*rightchild;
};
template<class T>class bitree
{
private:
void create(binode<T>*&R,T data[],int i,int n);
public:
binode<T>*root;
void bitree_creat(T data[],int n);
void preorder(binode<T>*R);
void levelorder(binode<T>*R);
void inorder(binode<T>*R);
void postorder(binode<T>*R);
int count_leaf(binode<T>*R);
binode<T>*getroot()
{
return root;
}
};
template<class T>
void bitree<T>::create(binode<T> *&R, T *data, int i,int n)
{
if((data[i-1]!=0)&&(i<n))
{
R=new binode<T>;
R->data=data[i-1];
R->leftchild=NULL;
R->rightchild=NULL;
create(R->leftchild,data,2*i,n);
create(R->rightchild,data,2*i+1,n);
}
else
{
R=NULL;
}
}
template<class T>
void bitree<T>::bitree_creat(T data[],int n)
{
root=NULL;
create(root,data,1,n);
}
template<class T>
void bitree<T>::preorder(binode<T> *R)
{
if(R!=NULL)
{
cout<<R->data;
preorder(R->leftchild);
preorder(R->rightchild);
}
}
template<class T>
void bitree<T>::inorder(binode<T> *R)
{
if(R!=NULL)
{
inorder(R->leftchild);
cout<<R->data;
inorder(R->rightchild);
}
}
template<class T>
void bitree<T>::postorder(binode<T> *R)
{
if(R!=NULL)
{
postorder(R->leftchild);
postorder(R->rightchild);
cout<<R->data;
}
}
template<class T>
void bitree<T>::levelorder(binode<T> *R)
{
binode<T>*queue[128];
int front=-1;
int rear=-1;
if(R!=NULL)
{
queue[++rear]=R;
}
while (front!=rear)
{
R = queue[++front];
cout << R->data;
if (R->leftchild != NULL)
queue[++rear] = R->leftchild;
if (R->rightchild != NULL)
queue[++rear] = R->rightchild;
}
}
template<class T>
int bitree<T>::count_leaf(binode<T> *R)
{
if(R==NULL)
return 0;
else
{
int m= count_leaf(R->leftchild);
int n= count_leaf(R->rightchild);
return m+n+1;
}
}
int main() {
char s[]="abcdefg";
bitree<char>tree;
tree.bitree_creat(s,sizeof (s));
tree.preorder(tree.getroot());
cout<<endl;
tree.inorder(tree.getroot());
cout<<endl;
tree.postorder(tree.getroot());
cout<<endl;
tree.levelorder(tree.getroot());
cout<<endl;
cout<<tree.count_leaf(tree.getroot());
}
二叉树的创建与操作
最新推荐文章于 2024-08-15 05:02:54 发布