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

編程樹的遍歷

發布時間: 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);
}

熱點內容
星火雲伺服器 發布:2025-03-18 00:13:06 瀏覽:707
ci框架indexphp 發布:2025-03-18 00:11:16 瀏覽:678
編程設計基礎 發布:2025-03-18 00:09:36 瀏覽:299
寬頻撥號連接中賬戶密碼是什麼 發布:2025-03-17 23:49:06 瀏覽:359
android貪吃蛇 發布:2025-03-17 23:45:57 瀏覽:69
zbar源碼 發布:2025-03-17 23:42:18 瀏覽:771
水星wifi改密碼怎麼改 發布:2025-03-17 23:41:39 瀏覽:791
編程班表 發布:2025-03-17 23:41:34 瀏覽:882
網上鄰居訪問許可權 發布:2025-03-17 23:41:31 瀏覽:391
國行安卓11如何使用谷歌 發布:2025-03-17 23:40:52 瀏覽:147