日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据结构实验之二叉树的建立与遍历

發布時間:2024/8/23 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构实验之二叉树的建立与遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述

?? ? ? 已知一個按先序序列輸入的字符序列,如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;
}

總結

以上是生活随笔為你收集整理的数据结构实验之二叉树的建立与遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。