二叉树创建,遍历(类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/arthu6/article/details/81073315

代码:

#include<iostream>
#include<queue>
using namespace std;
//创建节点
struct Tnode
{
    char data;//数据域
    Tnode *rchild;//右孩子
    Tnode *lchild;//左孩子
};
//定义类
class Tree
{
public:
    Tree(){root=CreatTree(root);}
    ~Tree(){}
    Tnode *CreatTree(Tnode *&T);
    void PreOder(Tnode *T);
    void InOder(Tnode *T);
    void PosOder(Tnode *T);
    void LeverOder(Tnode *T);
    Tnode *root;
};
//创建二叉树
Tnode* Tree::CreatTree(Tnode *&T)//递归建树
{
    char a;
    cin>>a;
    if(a=='#') T=NULL;
    else
    {
        T=new Tnode;//对比之前new后加()
        T->data=a;
        T->lchild=CreatTree(T->lchild);//生成左子树
        T->rchild=CreatTree(T->rchild);//生成右子树
    }
    return T;
}
//前序遍历
void Tree::PreOder(Tnode *root)
{
    if(root)
    {
        cout<<root->data<<" ";//输出父亲节点
        PreOder(root->lchild);//输出左子树
        PreOder(root->rchild);//输出右子树
    }
}
//中序遍历
void Tree::InOder(Tnode *root)
{
    if(root)
    {
    InOder(root->lchild);
    cout<<root->data<<" ";
    InOder(root->rchild);
    }
}
//后序遍历
void Tree::PosOder(Tnode *root)
{
    if(root)
    {
        PosOder(root->lchild);
        PosOder(root->rchild);
        cout<<root->data<<" ";
    }
}
//层序遍历
//采用队列输出一节点的同时将其左右孩子入队,重复操作直至队列为空
void Tree::LeverOder(Tnode *root)
{
    if(root)
    {
        queue<Tnode*> Q;
        Q.push(root);
        while(!Q.empty())
        {
            Tnode *q=Q.front();
            Q.pop();
            cout<<q->data<<" ";
            if(q->lchild!=NULL) Q.push(q->lchild);
            if(q->rchild!=NULL) Q.push(q->rchild);
        }
    }
}
//main函数
int main()
{
    Tree A;
    cout<<endl<<"前序遍历:";
    A.PreOder(A.root);
    cout<<endl<<"中序遍历:";
    A.InOder(A.root);
    cout<<endl<<"后序遍历:";
    A.PosOder(A.root);
    cout<<endl<<"层序遍历:";
    A.LeverOder(A.root);
    return 0;
}

截图:

猜你喜欢

转载自blog.csdn.net/arthu6/article/details/81073315