求二叉樹的高,節點個數,遍曆二叉樹

來源:互聯網
上載者:User
#include "stdio.h"
#include "malloc.h"
#include "math.h"
#include "string.h"
#define MAX 100
void exit(int);
/*--------------------*/



int count; /* 記錄二叉樹中的二度結點的個數 */
int flag; /* 標明二叉樹是否為AVL樹 */



/*--------------------*/



typedef struct node{
char d;
struct node *lchild,*rchild;
}TNode;

/*-----通過中序序列和後序序列建樹-----*/



void MkTree(char in[],int is,int ie,char post[],int posts,int poste,TNode **r)
{
int i;
if(is>ie || posts>poste)
*r=NULL;
else{
*r=malloc(sizeof(TNode));
(*r)->d=post[poste];
for(i=is;i<=ie;i++)
if(post[poste]==in){
MkTree(in,is,i-1,post,posts,posts+i-is-1,&(*r)->lchild);
MkTree(in,i+1,ie,post,posts+i-is,poste-1,&(*r)->rchild);
break;
}
if(i>ie){
printf("error:input contains an error!/n");
exit(9);
}
}
}



/*-----前序走訪二叉樹-----*/



void preorder(TNode *r)
{
if(r){
printf("%c",r->d);
preorder(r->lchild);
preorder(r->rchild);
}
}

/*-----求二叉樹中二度結點的個數-----*/



void BNode(TNode *r)
{
if(r){
if(r->lchild&&r->rchild)
count++;
BNode(r->lchild);
BNode(r->rchild);
}
}



/*-----求二叉樹中葉子的個數-----*/



int leaf(TNode *r)
{
if(r==NULL)
return 0;
else
if(r->lchild==NULL && r->rchild==NULL)
return 1;
else
return leaf(r->lchild) + leaf(r->rchild);
}



/*-----求二叉樹中葉子的高度-----*/



int Height(TNode *r)
{
int h1,h2;
if(r==NULL)
return 0;
else{
h1=Height(r->lchild);
h2=Height(r->rchild);
if(abs(h1-h2)>1)
flag=1;
return 1+(h1>h2?h1:h2);
}
}

void main()
{
TNode *r;
int height;
char post[MAX],in[MAX];
printf("Input inorder and postorder :/n");
gets(in);
gets(post);
MkTree(in,0,strlen(in)-1,post,0,strlen(post)-1,&r);
printf("The preorder is as follows:/n");
preorder(r);
printf("/nThere are %dletters in the tree./n",leaf(r));
count=0;
BNode(r);
printf("/nThere are %d binarynode in the tree./n",count);
flag=0;
height=Height(r);
printf("/nThe height of the tree is %d/n",height);
if(flag==1)
printf("/nThis bintree is not an AVL!/n");
else
printf("/nThis bintree is an AVL!/n");
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.