當前位置:首頁 » 編程軟體 » 編程樹的遍歷

編程樹的遍歷

發布時間: 2023-08-15 14:25:01

1. 編程實現以上二叉樹中序遍歷操作,輸出遍歷序列,求寫代碼~~

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

#define OK 1
#define ERROR 0
#define OVERFLOW 0

typedef char TElemType;
typedef int Status;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef enum {Link,Thread} PointerTag;
typedef struct BiThrNode
{
TElemType data;
struct BiThrNode *lchild,*rchild;
PointerTag LTag,RTag;
}BiThrNode;
typedef BiThrNode *BiThrTree;

BiTree CreateBiTree(BiTree T) //先序遍歷構造二叉樹
{
char ch;
scanf("%c",&ch);
if(ch=='#') //#代表空指針
T=NULL;
else
{
T=(BiTNode *)malloc(sizeof(BiTNode)); //申請結點
if(!T)
exit(OVERFLOW);
T->data=ch; //生成根結點
T->lchild=CreateBiTree(T->lchild); //構造左子樹
T->rchild=CreateBiTree(T->rchild); //構造右子樹
}
return T;
}

Status InOrderTraverse(BiTree T,Status(*visit)(TElemType))
{//中序遍歷二叉樹
if(T)
{
if(InOrderTraverse(T->lchild,visit))
if(visit(T->data))
if(InOrderTraverse(T->rchild,visit))
return OK;
return ERROR;
}
else
return OK;
}

Status PrintElement(TElemType e)
{
printf("%-2c",e);
return OK;
}

void main()
{
BiTree T=NULL;
printf("請輸入構造二叉樹的字元序列:");
T=CreateBiTree(T);
if(T)
printf("二叉樹建立成功! ");
else
printf("二叉樹構造失敗!!! ");
printf("中序遍歷二叉樹:");
InOrderTraverse(T,PrintElement);
printf(" ");
}

2. 急求C語言寫二叉樹的遍歷

下面是一個用
遞歸方法
編的二叉樹遍歷程序,供lz參考。
#include
<stdio.h>//頭文件
#include
<stdlib.h>
#include
<malloc.h>
typedef
struct
bitnode
{
char
data;
struct
bitnode
*lchild,*rchild;
}
bitnode,*bitree;//定義結點類型
bitree
createbitree()//創建樹
{
char
p;bitree
t;
scanf("%c",&p);
if(p=='
')
t=null;
else
{
t=(bitnode
*)malloc(sizeof(bitnode));//為結點開辟空間
t->data=p;
t->lchild=createbitree();
t->rchild=createbitree();
}
return
(t);
}
void
preorder(bitree
t)//
先序
{
if(t!=null)
{
printf("%c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void
inorder(bitree
t)//
中序
{
if(t!=null)
{
inorder(t->lchild);
printf("%c",t->data);
inorder(t->rchild);
}
}
void
postorder(bitree
t)//
後序
{
if(t!=null)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%c",t->data);
}
}
void
main()//主函數
{
bitree
ta;
ta=createbitree();
printf("先序遍歷:");
printf("\n");
preorder(ta);
printf("\n");
printf("中序遍歷:");
printf("\n");
inorder(ta);
printf("\n");
printf("後序遍歷:");
printf("\n");
postorder(ta);
}

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:577
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:869
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:566
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:748
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:668
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:992
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:239
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:97
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:790
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:696