二叉樹的創建一數據結構一C++


#include <iostream>
using namespace std;
//二叉樹結點
typedef struct BitNode               
{
    char ch;
    struct BitNode *lchild,*rchild;
}BitNode,*BitTree;
//創建鏈式隊列的方法
/*
typedef struct QNode
{
    BitNode *tree;
    struct QNode *next;
}QNode,*Queueptr;
typedef struct
{
    Queueptr fro;
    Queueptr rear;
}LinkQueue;
*/
//按照先序創建二叉樹
void CreatBitTree(BitTree &T)
{
    char c;
    cin>>c;
    if(c=='#')
        T = NULL;
    else
    {
        T = new BitNode;
        T -> ch = c;
        CreatBitTree(T -> lchild);
        CreatBitTree(T -> rchild);
    }
}
//將二叉樹按照先序輸出
void Print1(BitTree T)
{
    if(T != NULL)
    {
        cout<<T -> ch;
        Print1(T -> lchild);
        Print1(T -> rchild);
    }
}
//將二叉樹按照中序輸出
void Print2(BitTree T)
{
    if(T != NULL)
    {
        Print2(T -> lchild);
        cout<<T -> ch;
        Print2(T -> rchild);
    }
}
//將二叉樹按照后序輸出
void Print3(BitTree T)
{
    if(T != NULL)
    {
        Print3(T -> lchild);
        Print3(T -> rchild);
        cout<<T -> ch;
    }
}
//將二叉樹按照層次輸出
void Print4(BitTree T)
{
    int m=10,i=0,fro=0,rear=0;
    BitTree *a = new BitTree[m];
    BitNode *t,*t1;
    a[rear] = T;
    cout<<a[rear] -> ch;
    rear = (rear+1)%(m+1);      //最大a[10]
    while(fro != rear)
    {
        t = a[fro];
        fro = (fro+1)%(m+1);      //讀取一個雙親並刪除
        if(t -> lchild)
        {
            t1 = t -> lchild;
            a[rear] = t1;
            rear = (rear+1)%(m+1);
            cout<<t1 -> ch;
        }
        if(t -> rchild)
        {
            t1 = t -> rchild;
            a[rear] = t1;
            rear = (rear+1)%(m+1);
            cout<<t1 -> ch;
        }
    }
}
int Show(BitTree T)
{
    int n;
    cout<<"請輸入遍歷的順序 1:先序遍歷 2:中序遍歷 3:后序遍歷 4:層次遍歷 5:退出程序"<<endl;
    cin>>n;
    switch(n)
    {
    case 1:
        {
            Print1(T);
            cout<<endl;
        }
        break;
    case 2:
        {
            Print2(T);
            cout<<endl;
        }
        break;
    case 3:
        {
            Print3(T);
            cout<<endl;
        }
        break;
    case 4:
        {
            Print4(T);
            cout<<endl;
        }
        break;
    case 5:
        {
            cout<<"程序退出成功"<<endl;
            return 0;
        }
        break;
    default:
        cout<<"輸入有誤,重新輸入"<<endl;
        break;
    }
}
int main()
{
    int m=1;
    cout<<"請按照先序輸入:"<<endl;
    BitTree T;
    CreatBitTree(T);
    while(m!=0)
    {
      m=Show(T);
    }
    return 0;
}
/*
測試用例
ABC##DE#G##F###
*/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM