二叉树采用非递归算法求二叉树的叶子节点数(采用二叉链表存储结构)求更正,找个师傅
#include <stdio.h>#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5
typedef int Status;
typedef char Selemtype;
int n=0;
typedef struct{
Selemtype *base;
Selemtype *top;
int stacksize;
}Sqstack;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status Initstack (Sqstack &s){
s.base=(Selemtype *)malloc(STACK_INIT_SIZE * sizeof(Selemtype));
if(!s.base) exit(OVERFLOW);
s.top=s.base;
s.stacksize=STACK_INIT_SIZE;
return OK;
}
Status Pop(Sqstack &s,Selemtype &e){
if (s.top ==s.base) return ERROR;
e=*--s.top ;
return OK;
}
Status Push(Sqstack &s,Selemtype e){
if(s.top -s.base >=s.stacksize ){
s.base=(Selemtype *)realloc (s.base,(s.stacksize +STACKINCREMENT)* sizeof(Selemtype));
if(!s.base) exit (OVERFLOW);
s.top=s.base +s.stacksize;
s.stacksize +=STACKINCREMENT;
}
*s.top ++=e;
return OK;
}
Status StackEmpty(Sqstack s){
if(s.base ==s.top ) return TRUE;
else return FALSE;
}
Status CreateBiTree (BiTree &T){
char ch;
ch=getchar();
if(ch==' ') T=NULL;
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) exit(OVERFLOW);
T->data =ch;
CreateBiTree(T->lchild );
CreateBiTree(T->rchild );
}
return OK;
}
Status perorder (BiTree &T){
Sqstack s;
BiTree p;
Initstack(s);
Push(s,T);
while(!StackEmpty(s)){
Pop(s,p);
while(p){
if(!p->lchild&&!p->rchild) n++;
Push(s,p->rchild);
p=p->lchild;
}
}
return OK;
}
int main()
{
BiTree T;
printf("请输入二叉树:");
CreateBiTree(T);
perorder(T);
printf("该二叉树的叶子结点数为:%d",n);
return OK;
} 数据结构 自己找答案吧 int count(struct Node *root)
{
int n=0;
stack s;
if(root == null) return 0;
s.push(root);
while(!s.empty()){
p = s.pop();
if(p->left == null && p->right==null){
n++;
}
if(p->left != null){
s.push(p->left);
}
if(p->right != null){
s.push(p->right);
}
return n;
} 无敌小儿 发表于 2019-10-16 19:57
int count(struct Node *root)
{
int n=0;
一直忘了感谢了,非常谢谢。
页:
[1]