最近在學習C語言的基礎知識。
正好,今天爲一個同學講二叉樹的創建與排序。將最近複習的知識又重新梳理了一下,順便記錄下二叉樹實現的具體代碼。
1、二叉樹節點的存儲結構
- typedef struct BiTNode
- {
- ElemType data;
- struct BiTNode*lchild,*rchild;//左右孩子指針
- } BiTNode,*BiTree;
2 利用前驅遍歷的方式,創建二叉樹,
3 利用遞歸的方式,前序、中序、後序遍歷二叉樹
- #include <stdlib.h>
- #include <stdio.h>
- typedef char ElemType;//每個元素的數據類型爲ElemType。假設爲char
- typedef struct BiTNode
- {
- ElemType data;
- struct BiTNode*lchild,*rchild;//左右孩子指針
- } BiTNode,*BiTree;
- //打印主界面
- void printMain()
- {
- printf("**********************************************************\n");
- printf("\t 1、建立二叉樹\n");
- printf("\t 2、前序遍歷二叉樹\n");
- printf("\t 3、中序遍歷二叉樹\n");
- printf("\t 4、後序遍歷二叉樹\n");
- printf("\t 0、結束\n");
- printf("**********************************************************\n");
- }
- //創建二叉樹
- BiTree CreateBiTree(BiTree T)
- {
- char ch;
- ch=getchar();
- if(ch=='#')
- T=NULL;
- else{
- if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
- printf("Error!");
- T->data=ch;
- T->lchild=CreateBiTree(T->lchild);
- T->rchild=CreateBiTree(T->rchild);
- }
- return T;
- }
- //前序遍歷
- void PreOrder(BiTNode *root)
- {
- if(root==NULL) return;
- printf("%c",root->data);
- PreOrder(root->lchild);
- PreOrder(root->rchild);
- }
- //中序遍歷
- void InOrder (BiTNode *root)
- {
- if(root==NULL)
- return;
- InOrder(root->lchild);
- printf("%c",root->data);
- InOrder(root->rchild);
- }
- //後序遍歷
- void PostOrder(BiTNode *root)
- {
- if(root==NULL)
- return;
- PostOrder(root->lchild);
- PostOrder(root->rchild);
- printf("%c",root->data);
- }
- int main()
- {
- BiTree A=NULL;
- int i;
- do{
- // system("cls");
- printMain();
- printf("請選擇操作數(1,2,3,4,0):");
- scanf("%d",&i);
- switch(i)
- {
- case 1:
- {
- printf("創建二叉樹:");
- A = CreateBiTree(A);
- break;
- }
- case 2:
- {
- printf("前序遍歷二叉樹:");
- PreOrder(A);
- break;
- }
- case 3:
- {
- printf("中序遍歷二叉樹:");
- InOrder(A);
- break;
- }
- case 4:
- {
- printf("後序遍歷二叉樹:");
- PostOrder(A);
- break;
- }
- case 0:
- exit(0);
- }
- printf("\n");
- }while( i==1 || i==2 || i==3 || i==4 || i==0 );
- return 0;
- }