数据结构实验之二叉树的建立与遍历
生活随笔
收集整理的這篇文章主要介紹了
数据结构实验之二叉树的建立与遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
?? ? ? 已知一個按先序序列輸入的字符序列,如abc,,de,g,,f,,,(其中逗號表示空節點)。請建立二叉樹并按中序和后序方式遍歷二叉樹,最后求出葉子節點個數和二叉樹深度。輸入
?輸入一個長度小于50個字符的字符串。輸出
輸出共有4行:第1行輸出中序遍歷序列;
第2行輸出后序遍歷序列;
第3行輸出葉子節點個數;
第4行輸出二叉樹深度。
示例輸入
abc,,de,g,,f,,,示例輸出
cbegdfa cgefdba 3 5提示
#include<stdio.h>#include<string.h>
#include<stdlib.h>
typedef char Status;
typedef char telemtype;
typedef struct BiTNode
{
? ? Status data;
? ? struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status str[55];
int i,count;
int CreateBiTree(BiTree &T)//建二叉樹;
{
? ? ? ? if(str[i++]==',') T=NULL;
? ? ? ? else
? ? ? ? {
? ? ? ? T=(BiTNode *)malloc(sizeof(BiTNode));
? ? ? ? if(!T)
? ? ? ? exit(0);
? ? ? ? T->data=str[i-1];
? ? ? ? CreateBiTree(T->lchild);
? ? ? ? CreateBiTree(T->rchild);
? ? ? ?}
? ? return 1;
}
void inorder(BiTree &T)//中序二叉樹
{
? ? if(T)
? ? {
? ? ? ? inorder(T->lchild);
? ? ? ? printf("%c",T->data);
? ? ? ? inorder(T->rchild);
? ? }
}
void postorder(BiTree &T)//后序二叉樹
{
? ? if(T)
? ? {
? ? ? ?postorder(T->lchild);
? ? ? ?postorder(T->rchild);
? ? ? ?printf("%c",T->data);
? ? }
}
void CountLeaf(BiTree T,int &count)//樹中葉子的統計;
{
? ? if(T)
? ? {
? ? ? ? if((!T->rchild)&&(!T->lchild))
? ? ? ? ? ? ++count;
? ? ? ? CountLeaf(T->rchild,count);
? ? ? ? CountLeaf(T->lchild,count);
? ? }
}
int depth(BiTree T)//樹的深度;
{
? ? int lth,rth;
? ? if(!T) ?return 0;
? ? else
? ? {
? ? ? ? lth=depth(T->lchild);
? ? ? ? rth=depth(T->rchild);
? ? ? ? if(lth>rth)
? ? ? ? ? ? return lth+1;
? ? ? ? else
? ? ? ? ? ? return rth+1;
? ? }
}
int main()
{
? ? BiTree T;
? ? while(~scanf("%s",str))
? ? {
? ? ? ?i=0;
? ? ? ?CreateBiTree(T);//生成樹;
? ? ? ?inorder(T);//中序二叉樹
? ? ? ?printf("\n");
? ? ? ?postorder(T);//后序二叉樹
? ? ? printf("\n");
? ? ? count=0;
? ? ? CountLeaf(T,count);//樹葉子的統計;
? ? ? printf("%d\n",count);
? ? ? int h=depth(T);//樹深度;
? ? ? printf("%d\n",h);
? ? }
? ? return 0;
}
總結
以上是生活随笔為你收集整理的数据结构实验之二叉树的建立与遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt程序崩溃原因
- 下一篇: html中怎么自动获得搜索文本框的光标焦