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

#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);
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值