數據結構 遞歸遍歷二叉樹 C/C++

#include<stdio.h>
#include<stdlib.h>

typedef struct btnode
{
    char data;
    struct btnode *lchild,*rchild;
}btnode,*bitree;
bitree Creatbintree()               //前序遍歷創建二叉樹
{
    char ch;
    bitree bt;
    scanf("%c",&ch);
    if(ch=='#') bt=NULL;
    else
    {
        bt=(btnode*)malloc(sizeof(btnode));
        bt->data=ch;
        bt->lchild=Creatbintree();
        bt->rchild=Creatbintree();
    }
    return bt;
}
void Preorder(bitree bt)                //前序遍歷
{
    if(bt==NULL) return;
    printf("%c ",bt->data);
    Preorder(bt->lchild);
    Preorder(bt->rchild);
}
void Inorder(bitree bt)                 //中序遍歷
{
    if(bt==NULL) return;
    Preorder(bt->lchild);
    printf("%c ",bt->data);
    Preorder(bt->rchild);
}
void Posorder(bitree bt)                //後序遍歷
{
    if(bt==NULL) return;
    Preorder(bt->lchild);
    Preorder(bt->rchild);
    printf("%c ",bt->data);
}
int main()
{
    bitree bt;
    printf("請按前序遍的次序歷輸入二叉樹(空節點爲#):\n");
    bt=Creatbintree();
    printf("前序遍歷得到的次序\n");
    Preorder(bt);
    printf("\n中序遍歷得到的次序\n");
    Inorder(bt);
    printf("\n後序遍歷得到的次序\n");
    Posorder(bt);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章