您的位置:首页 > 其它

二叉树递归的基本操作(求叶子数目、深度、路径汇总)

2011-08-02 16:48 519 查看
#include <stdio.h>

#include <malloc.h>

#include <stdlib.h>

#define STACKMAX 20

typedef char Elemtype;

typedef int status;

typedef struct node

{

Elemtype data;

struct node *lchild,*rchild;

}*BiTree,BiTNode;

typedef Elemtype StackElemtype;

typedef struct

{

StackElemtype base[STACKMAX];

int top;

}SqStack;

/*---------------栈的基本操作-----------*/

void InitStack(SqStack *S)

{

S->top=0;

}

void Push(SqStack *S,StackElemtype e)

{

S->base[S->top++]=e;

}

void Pop(SqStack *S)

{

if(S->top==0)

printf("The Stack is Empty\n");

S->top--;;

}

StackElemtype GetTop(SqStack *S)

{

if(S->top==0) exit(0) ;

return S->base[S->top-1];

}

int StackEmpty(SqStack *S)

{

if(S->top==0)

return 1;

else

return 0;

}

void TraverseStack(SqStack *S)

{

int i=0;

while(i<S->top)

{

printf("%c ",S->base[i]);

i++;

}

}

/*---------------树的基本操作-----------*/

BiTree CreateBiTree () //按先序遍历次序输入结点的值

{

BiTree T;

Elemtype ch;

scanf("%c",&ch);

if(ch=='/') T=NULL;

else

{

if(T=( BiTNode *)malloc(sizeof(BiTNode)))

T->data=ch;

T->lchild=CreateBiTree (); //将新结点插入左子树

T->rchild=CreateBiTree (); //将新结点插入右子树

}

return T;

}

status DepthTree(BiTree T)

{

int ld,rd;

ld=rd=0; //此地不初始化也可以

if(!T) return 0;

ld=DepthTree(T->lchild);

rd=DepthTree(T->rchild);

if(ld>rd)

return ld+1;

else

return rd+1;

}

status CountLeaf(BiTree T)

{

int lc,rc;

lc=rc=0; //初始化叶子数

if(T)

{

if(T->lchild==NULL&&T->rchild==NULL)

return 1;

else

{

lc=CountLeaf(T->lchild);

rc=CountLeaf(T->rchild);

return lc+rc;

}

}

}

void PathTree(BiTree T,SqStack *S)

{

if(T)

{

Push(S,T->data);

if(T->lchild==NULL&&T->rchild==NULL)

{

TraverseStack(S);

printf("\n");

}

else

{

PathTree(T->lchild,S); //输出根到所有左子树叶子结点的路径

PathTree(T->rchild,S); //输出根到所有右子树叶子结点的路径

}

Pop(S); //当前根退栈

}

}

void main()

{

BiTree T;

SqStack S;

InitStack(&S);

T=CreateBiTree();

printf("The depth of the Tree is:%d\n",DepthTree(T));

printf("The amount of the leafs is:%d\n",CountLeaf(T));

printf("根到所有叶子结点的路径依次是:\n");

PathTree(T,&S);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐