1. 程式人生 > >二叉樹增加一個自身數目域並賦值

二叉樹增加一個自身數目域並賦值

#include<stdio.h>
#include<malloc.h>
#define null 0

struct Btree{
char data;
int DescNum;
Btree *lchild;
Btree *rchild;
};

Btree *setup()
{
char ch;
Btree *bt;
printf(“please input ch:”);
ch=getchar();
getchar();
if(ch!=’.’)
{
bt=(Btree *)malloc(sizeof(Btree));
bt->data=ch;
bt->lchild=setup();
bt->rchild=setup();
}
else
return null;
}

int number(Btree *root)
{
if(!root->lchild&&!root->rchild)
{root->DescNum=0;return 0;}
else if(root->lchild&&root->rchild)
{root->DescNum=number(root->lchild)+number(root->rchild)+2;
return root->DescNum;}
else if(root->lchild)
{root->DescNum=number(root->lchild)+1;
return root->DescNum;}
else
{root->DescNum=number(root->rchild)+1;
return root->DescNum;
}
}

int main()
{
Btree *b1;
b1=setup();
printf("%d",number(b1));
return 0;
}

輸入a
b
.
c
.
.
d
.
.
輸出a的子孫數3