1. 程式人生 > >資料結構學習——二叉樹遍歷

資料結構學習——二叉樹遍歷

  1 #include"stdio.h"
  2 #include"stdlib.h"
  3 #define maxsize 100
  4 //二叉樹連結串列型別定義 
  5 typedef struct node{
  6     char data;
  7     struct node *lchild;//左指標 
  8     struct node *rchild;//右指標 
  9 }BTreeNode;
 10 //二叉樹建立 
 11 BTreeNode *create(){
 12     BTreeNode *s;
 13     BTreeNode *q[maxsize];//設定陣列,存放每個結點的地址值
14 int i,j; 15 char x; 16 printf("***開始建立***\n"); 17 printf("i,x="); 18 scanf("%d,%c",&i,&x); 19 if(i==0)//如果二叉樹為空 20 { 21 q[1]=NULL; 22 } 23 while(i!=0&&x!='s')//當i=0,x='s',結束結點建立 24 { 25 s=(BTreeNode*)malloc(sizeof(BTreeNode));//
申請記憶體 26 s->data=x; 27 s->lchild=NULL; 28 s->rchild=NULL; 29 q[i]=s; 30 if(i!=1)//非根節點,尋找雙親結點的地址 31 { 32 j=i/2;//j為雙親結點的地址 33 if(i%2==0)//左孩子 34 { 35 q[j]->lchild=s; 36 } else
{//右孩子 37 q[j]->rchild=s; 38 } 39 } 40 printf("i,x="); 41 scanf("%d,%c",&i,&x); 42 } 43 44 45 return q[1];//返回根結點 46 } 47 48 //二叉樹遍歷 49 //1、先序遍歷 50 void preOrder(BTreeNode *Tree){ 51 if(Tree){ 52 printf("%c",Tree->data);//輸出根結點 53 preOrder(Tree->lchild);//左結點輸出 54 preOrder(Tree->rchild);//右結點輸出 55 } 56 57 } 58 //中序遍歷 59 void inOrder(BTreeNode *Tree){ 60 if(Tree){ 61 inOrder(Tree->lchild);//左結點輸出 62 printf("%c",Tree->data);//輸出根結點 63 inOrder(Tree->rchild);//右結點輸出 64 } 65 66 } 67 //後序遍歷 68 void postOrder(BTreeNode *Tree){ 69 if(Tree){ 70 postOrder(Tree->lchild);//左結點輸出 71 postOrder(Tree->rchild);//右結點輸出 72 73 printf("%c",Tree->data);//輸出根結點 74 75 } 76 77 } 78 //層次遍歷 79 void levelOrder(BTreeNode *Tree){ 80 BTreeNode *p,*q[maxsize]; 81 int rear=0,front=0; 82 if(Tree){ 83 p=Tree; 84 q[rear]=p;//根結點入隊 85 rear=(rear+1)%maxsize;//尾指標後移 86 while(front!=rear)//當佇列不為空 87 { 88 p=q[front];//取隊頭元素 89 printf("%c",p->data); 90 front=(front+1 )%maxsize;//頭指標後移 91 if(p->lchild){//如果左孩子不為空,左孩子入隊 92 q[rear]=p->lchild; 93 rear=(rear+1)%maxsize; 94 } 95 if(p->rchild){//如果右孩子不為空,右孩子入隊 96 q[rear]=p->rchild; 97 rear=(rear+1)%maxsize; 98 } 99 } 100 } 101 102 } 103 int main(){ 104 BTreeNode *Tree=create();//建立二叉樹 105 printf("先序遍歷:\n"); 106 preOrder(Tree); 107 printf("\n中序遍歷:\n"); 108 inOrder(Tree); 109 printf("\n後序遍歷:\n"); 110 postOrder(Tree); 111 printf("\n層次遍歷:\n"); 112 levelOrder(Tree); 113 114 }