c++数据结构 二叉链表的实现

#include
using namespace std;

struct binode
{
    char data;
    binode*lchild, *rchild;
};

class bitree
{
public:
    bitree();
    ~bitree();
    void preorder();
    void inorder();
    void postorder();
private:
    binode*root;//指向根结点指针
    binode*create(binode*bt);//构造函数调用
    void release(binode*bt);//析构函数调用
    void preorder(binode*bt);//前序遍历函数调用
    void inorder(binode*bt);
    void postorder(binode*bt);
};

bitree::bitree()
{
    root = create(root);
}

bitree::~bitree()
{
    release(root);
}
void bitree::preorder()
{
    preorder(root);
}

void bitree::inorder()
{
    inorder(root);
}

void bitree::postorder()
{
    postorder(root);
}

binode*bitree::create(binode*bt)
{
    char ch;
    cin >> ch;
    if (ch == '#')return NULL;
    else
    {
        bt = new binode;
        bt->data = ch;
        bt->lchild = create(bt->lchild);//前序遍历递归建立树
        bt->rchild = create(bt->rchild);
    }
    return bt;
}

void bitree::release(binode*bt)
{
    if (bt != NULL)
    {
        release(bt->lchild);
        release(bt->rchild);
        delete bt;
    }
}

void bitree::preorder(binode*bt)
{
    if (bt == NULL)return;
    else
    {
        cout << bt->data << " ";
        preorder(bt->lchild);
        preorder(bt->rchild);
    }
}

void bitree::inorder(binode*bt)
{
    if (bt == NULL)return;
    else
    {
        inorder(bt->lchild);
        cout << bt->data << " ";
        inorder(bt->rchild);

    }
}

void bitree::postorder(binode*bt)
{
    if (bt == NULL)return;
    else
    {
        postorder(bt->lchild);
        postorder(bt->rchild);
        cout << bt->data << " ";
    }
}

int main()
{
    bitree t;//create a tree 
    cout << "---------------前序遍历为----------------" << endl;
    t.preorder();
    cout << endl;
    cout << "---------------中序遍历为----------------" << endl;
    t.inorder();
    cout << endl;
    cout << "---------------后续遍历为----------------" << endl;
    t.postorder();
    cout << endl;
    return 0;
}

你可能感兴趣的:(数据结构,c++)