二叉树的创建与操作

#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());



}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值