1. 程式人生 > >二叉樹先中後序遍歷的C++程式碼

二叉樹先中後序遍歷的C++程式碼

馬上就要資料結構考試了,會考到二叉樹的遍歷演算法設計題,然後就自己總結了一個關於二叉樹的簡單演算法程式碼。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX  100
using namespace std;
//二叉樹的儲存結構
typedef struct bit

{
    char data;
    struct bit *lchild,*rchild;

}bitnode,*bitree;
bitree createbitree(bitree t)
{
    char ch;
    cin>>ch;
    if(ch=='#') t=0;

    else
    {
    t=(bitnode*)malloc(sizeof(bitnode));
    if(!t) exit(-2);
    t->data=ch;
    t->lchild=createbitree(t->lchild);
    t->rchild=createbitree(t->rchild);
    }
    return t;
}
//二叉樹的中序遍歷

void inorderzhong(bitree t)
{
    if(t)
    {
        inorderzhong(t->lchild);
        cout<<t->data;
        inorderzhong(t->rchild);
    }
}
//二叉樹的先序遍歷
void inorderxian(bitree t)
{
    if(t)
    {
        cout<<t->data;
        inorderxian(t->lchild);

        inorderxian(t->rchild);
    }
}
//二叉樹的後序遍歷
void inorderhou(bitree t)
{
    if(t)
    {

        inorderhou(t->lchild);

        inorderhou(t->rchild);
        cout<<t->data;
    }
}
int main()
{
    bitree b=0,t=0;
    cout<<"構造一顆二叉樹並對其進行遍歷"<<endl;
    cout<<"請輸入構造二叉樹的字元序列:";
    b=createbitree(t);
    if(b)
    {
        cout<<"先序遍歷:";
        inorderxian(b);
        cout<<endl;
        cout<<"中序遍歷:";
        inorderzhong (b);
        cout<<endl;
        cout<<"後序遍歷:";
        inorderhou(b);
        cout<<endl;
    }
    else
    {
        cout<<"失敗";
    }
    return 0;
}

驗證過成功,這個程式碼通俗易懂,看上幾遍後自己試著寫寫就可以過。