二叉树的递归遍历(先序,中序,后序)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的递归遍历(先序,中序,后序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include "stdio.h"
#include "malloc.h"
#define M 100
typedef struct node
{ /* 采用二叉鏈表存儲結構 */char data;struct node *lchild,*rchild;
}BTnode;
BTnode *create()/*利用先序遍歷的過程創建二叉樹*/
{BTnode *t;char ch;scanf("%c",&ch);if(ch=='#')t=NULL;else{t=(BTnode *)malloc(sizeof(BTnode)) ;t->data=ch;t->lchild=create();t->rchild=create();}return t;
}
void preorder(BTnode *t)/*先序遍歷二叉樹*/
{if(t!=NULL)printf("%c ",t->data);if(t->lchild!=NULL)preorder(t->lchild);if(t->rchild!=NULL)preorder(t->rchild);}
void inorder(BTnode *t)/*中序遍歷二叉樹*/
{if(t!=NULL){if(t->lchild!=NULL)inorder(t->lchild);printf("%c ",t->data);if(t->rchild!=NULL)inorder(t->rchild);}
}
void postorder(BTnode *t)/*后序遍歷二叉樹*/
{if(t!=NULL){ if(t->lchild!=NULL)postorder(t->lchild);if(t->rchild!=NULL)postorder(t->rchild);printf("%c ",t->data);}
}
void main()
{
BTnode *t;
printf("Input data:") ;
t=create();
printf("==================The result==========================\n");
printf("The preorder is:\n");
preorder(t);
printf("\n");
printf("The inorder is:\n");
inorder(t);
printf("\n");
printf("The postorder is:\n");
postorder(t);
printf("\n");
}
總結
以上是生活随笔為你收集整理的二叉树的递归遍历(先序,中序,后序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity3D 发布APK安卓环境配置步
- 下一篇: 一维数组的定义方式