#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node*rchild,*lchild;
}btnode;
btnode *create()
{
btnode*t;
int m;
if(scanf("%d",&m)!=1)
t=NULL;
else
{
t=(btnode*)malloc(sizeof(btnode));
t->data=m;
t->lchild=create();
t->rchild=create();
}
return t;
}
int gettwo(btnode*bt,int n)
{
if(bt!=NULL)
{
if(bt->lchild&&bt->rchild)
return n+1;
gettwo(bt->lchild,n);
gettwo(bt->rchild,n);
}
}
void inorder(btnode*bt)
{
if(bt!=NULL)
{
printf("%d ",bt->data);
inorder(bt->lchild);
inorder(bt->rchild);
}
}
void main()
{
btnode*p;
int m=0,k=0;
p=create();
inorder(p);
printf("\n");
k=gettwo(p,m);
printf("度数为2的节点个数为:%d\n",k);
}
int gettwo(btnode*bt,int m)
{
static int n=0; //定义全局变量 因为每次的n都会变化
if(bt!=NULL)
{
if(bt->lchild&&bt->rchild)
n=n+1;
gettwo(bt->lchild,n);
gettwo(bt->rchild,n);
return n;//你的代码return位置不对 你的意思 只要看到有一个 就返回了函数调用,如果
} //根节点就是双分支呢?
#define use _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *rchild,*lchild;
}btnode;
btnode *create()
{
btnode *t;
int m;
scanf_s("%d",&m);
if(m==0)
return t=NULL;
else
{
t=(btnode*)malloc(sizeof(btnode));
t->data=m;
t->lchild=create();
t->rchild=create();
}
return t;
}
int gettwo(btnode*bt,int m)
{
static int n=0;
if(bt!=NULL)
{
if(bt->lchild&&bt->rchild)
n=n+1;
gettwo(bt->lchild,n);
gettwo(bt->rchild,n);
return n;
}
}
void inorder(btnode*bt)
{
if(bt!=NULL)
{
printf("%d ",bt->data);
inorder(bt->lchild);
inorder(bt->rchild);
}
}
void main()
{
btnode *p;
int m=0,k=0;
p=create();
inorder(p);
printf("\n");
k=gettwo(p,m);
printf("度数为2的节点个数为:%d\n",k);
getchar();getchar();
system("pause");
}
追问是不是我原来写的那个:如果根节点有两个分支,函数就直接return了,不执行下面的递归语句了?所以要把左右子树分开,在最后面return?
这个问题是由于输入缓冲区没有清空造成的
#include<stdio.h>为什么只是构建了左子数呢?我明明输入的是一颗完整的二叉树,可是为什么遍历时,跟我想象的输出不一样啊!那个scanf函数,当我初始化数组时中间打空格可以但是当我作为只要输入的不是整数作为递归的终结时就不行了?
追答scanf遇到与要求类型不符字符时,并不从缓冲区中清除该字符,返回上一层递归时继续执行,调用t->rchild=create();,在其中scanf再次读到这个字符,于是逐层返回,结束create。加上一个getchar,将缓冲区中的字符取走,再到scanf时,又会要求输入数值,顺序构建右子树了。
追问原来是这样子的!多谢了!