递归和非递归实现计算二叉树叶子节点的个数

#include
#include
#include 
#include 

#define MAXSIZE 50

typedef struct BinaryTree{
      char data;
      struct BinaryTree* pLeft;
      struct BinaryTree* pRight;
}BinaryTree;//Binary Tree Node

typedef struct StackTree{
      BinaryTree* b[MAXSIZE];
      int top;
};

//队列的结构体的表示形式
typedef struct queueelem
{
      BinaryTree* b[MAXSIZE];
      int front,rear;
}Queue;

//创建二叉树
BinaryTree* CreateBinaryTree()
{
      char cData;
      scanf_s("%c",&cData);
      getchar();
      if (cData == '#')
      {
            return NULL;
      }
      else
      {
            BinaryTree* pBTree = (BinaryTree*)malloc(sizeof(BinaryTree));
            if (NULL == pBTree)
            {
                  return NULL;
            }
            pBTree->data = cData;
            pBTree->pLeft = CreateBinaryTree();
            pBTree->pRight = CreateBinaryTree();
            return pBTree;
      }
}
//递归实现获取叶子节点个数
int ChildCount(BinaryTree* pBinayTree)
{
      if (NULL == pBinayTree)
      {
            return 0;
      }
      
      if (NULL == pBinayTree->pLeft && NULL == pBinayTree->pRight)
      {
            printf_s("%c ",pBinayTree->data);
            return 1;
      }
      return ChildCount(pBinayTree->pLeft)+ChildCount(pBinayTree->pRight);
}

//非递归实现获取叶子节点个数
int ChildCountTraverse(BinaryTree* pBinaryTree)
{
      if (NULL == pBinaryTree)
      {
            return 0;
      }
      if (NULL == pBinaryTree->pLeft && NULL == pBinaryTree->pRight)
      {
            printf_s("\n%c\n",pBinaryTree->data);
            return 1;
      }
      Queue queue;
      queue.front = queue.rear =0;
      queue.b[queue.front] = pBinaryTree;
      queue.rear++;
      int iCount = 0;
      while (queue.frontpLeft)
            {
                  queue.b[queue.rear] = (pBinaryTree->pLeft);
                  queue.rear++;
            }
            if (NULL != pBinaryTree->pRight)
            {
                  queue.b[queue.rear] = (pBinaryTree->pRight);
                  queue.rear++;
            }
            if (NULL == pBinaryTree->pLeft && NULL == pBinaryTree->pRight)
            {
                  iCount +=1;
                  printf_s("%c ",pBinaryTree->data);
            }
      }
      return iCount;
}

int  main()
{
      BinaryTree* pBinaryTree = CreateBinaryTree();
      printf_s("叶子节点的个数:\n");
      int iCount = ChildCount(pBinaryTree);
      printf_s("\nCount = %d\n",iCount);
      printf_s("叶子节点的个数:非递归\n");
      iCount = ChildCountTraverse(pBinaryTree);
      printf_s("\nCount = %d\n",iCount);
      return 0;
}

测试结果:

递归和非递归实现计算二叉树叶子节点的个数_第1张图片


你可能感兴趣的:(C++,二叉树)