資源描述:
《用c語言創(chuàng)建二叉樹并先序遍歷》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、用C語言創(chuàng)建二叉樹并先序遍歷程序制作:FEITK#include"stdio.h"#include"stdlib.h"typedefstructnode{chardata;structnodelchild,rchild;}BT;BTCreateBT(){BTq,s[30];inti,j;charx;printf("請(qǐng)輸入二叉樹的節(jié)點(diǎn)編號(hào)和節(jié)點(diǎn)數(shù)據(jù)(例:1,A)注意:結(jié)束輸入時(shí)節(jié)點(diǎn)編號(hào)輸入0,節(jié)點(diǎn)數(shù)據(jù)任意!");printf("編號(hào),數(shù)據(jù):");scanf("%d,%c",&i,&x);whi
2、le(i!=0){q=(BT)malloc(sizeof(BT));q->data=x;q->lchild=NULL;q->rchild=NULL;s[i]=q;if(i!=1){j=i/2;if(i%2==0)s[j]->lchild=q;elses[j]->rchild=q;}printf("編號(hào),數(shù)據(jù):");scanf("%d,%c",&i,&x);}returns[1];}voidPreorder(BTbt)/先序遍歷/{if(bt!=NULL){printf("%c",bt->data);Preord
3、er(bt->lchild);Preorder(bt->rchild);}}voidPreorder2(BTbt)/先序遍歷度為2的節(jié)點(diǎn)/{if(bt!=NULL){if(bt->lchild!=NULL&&bt->rchild!=NULL){printf("%c",bt->data);Preorder2(bt->lchild);Preorder2(bt->rchild);}}}voidPreorder1(BTbt)/先序遍歷度為1的節(jié)點(diǎn)/{if(bt!=NULL){if((bt->lchild==NULL&&
4、bt->rchild!=NULL)(bt->lchild!=NULL&&bt->rchild==NULL))printf("%c",bt->data);else{Preorder1(bt->lchild);Preorder1(bt->rchild);}}}voidPreorder0(BTbt)/先序遍歷度為0的節(jié)點(diǎn)/{if(bt!=NULL){if(bt->lchild==NULL&&bt->rchild==NULL)printf("%c",bt->data);else{Preorder0(bt->lchild
5、);Preorder0(bt->rchild);}}}main(){BTbt=CreateBT();printf("先序遍歷輸出所有節(jié)點(diǎn):");Preorder(bt);printf("");printf("先序遍歷輸出所有度為2的節(jié)點(diǎn):");Preorder2(bt);printf("");printf("先序遍歷輸出所有度為1節(jié)點(diǎn):");Preorder1(bt);printf("");printf("先序遍歷輸出所有度為0節(jié)點(diǎn):");Preorder0(bt);printf
6、("");system("pause");}