?? 二叉樹(shù)的高度、葉子節(jié)點(diǎn)數(shù).c
字號(hào):
#include<stdlib.h>
#include<stdio.h>
#define m0 100 //定義節(jié)點(diǎn)最大個(gè)數(shù)
static int NUM=0; //定義葉子個(gè)數(shù)
static int DEEP=0; //定義樹(shù)的深度
static int TEMP=0;
#define Len sizeof (BinNode) //定義存儲(chǔ)單元空間
typedef struct BinNode //定義節(jié)點(diǎn)類型
{
char data;
struct BinNode *lch,*rch;
} BinNode,*Bintree;
struct chtp
{
int len;
char ch[m0];
};
struct BinNode *bt,*m;
struct chtp s;
int top=0,i=0;
void crt_pre(Bintree *t) //遞歸建立二叉樹(shù)
{
char c;
c=s.ch[i];
i=i+1;
if (c=='.')
*t=NULL;
else
{
*t=(BinNode *)malloc(Len);
(*t)->data=c;
crt_pre(&(*t)->lch);
crt_pre(&(*t)->rch);
};
}
void preorder( BinNode *t,int temp) //先序遍歷二叉樹(shù),并在過(guò)程中計(jì)算深度和葉子數(shù)
{
int top=temp;
if(t!=NULL)
{
TEMP=top+1;
if((t->lch==NULL)&&(t->rch==NULL)) //無(wú)孩子節(jié)點(diǎn),即該點(diǎn)為葉子
{
NUM++;
if(TEMP>DEEP)DEEP=TEMP;
}
printf("%c",t->data);
preorder(t->lch,temp+1);
preorder(t->rch,temp+1);
}
}
void main()
{
char /*c[]={'a','b','d','.','.','.','c','e','.','.','f','.','.','!'};*/
c[]={'a','b','c','.','.','d','e','.','g','.','.','f','.','.','.','!'};
int i=0;
for(i=0,s.len=0;c[i]!='!';i++,s.len++)
s.ch[i]=c[i];
crt_pre(&bt);
preorder(bt,0);
printf("\n");
printf("高度為:%d\n",DEEP);
printf("葉子數(shù)為:%d",NUM);
printf("\n");
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -