实验五 二叉树的建立、遍历及应用

1、按照先序方法建立如图的二叉树: 2、按照中序分别用递归和非递归方法遍历 3、统计叶子节点的个数。


 #include<stdio.h>
#include<stdlib.h>
struct Tree
{
    int  data;
    struct Tree *Lchild;
    struct Tree *Rchild; 
 };
struct Tree *CreateTree(struct Tree  * tree)
 {
     int ch;
    scanf("%d",&ch);
    if(ch==0)
    tree=NULL;
     else
     {
         tree=(struct Tree * )malloc(sizeof(struct Tree));
         tree->data=ch;
         tree->Lchild=CreateTree(tree->Lchild);
         tree->Rchild=CreateTree(tree->Rchild);
          
     }
     return tree;
 }
void ListTree(struct Tree * tree)//中序递归遍历 
 {
     if(tree!= NULL)
     {
        ListTree(tree->Lchild);
         printf("%d\n",tree->data);
         ListTree(tree->Rchild);
     }
 }
 /*void ListTree(struct Tree * tree)//中序非递归遍历 
 {
    struct Tree * p;
    struct Tree *stack[20];
    int top=0;
    p=tree;
    while(p||top!=0)
    {
        while(p)
        {
            stack[top++]=p;
            p=p->Lchild;
        }
        p=stack[--top];
        printf("%d ",p->data);
        p=p->Rchild;
     } 
 }*/
void GetNum(struct Tree * tree,int &n )//统计叶子节点的个数 
 {
 
     if(tree !=NULL)
     {
         n++;
         GetNum(tree->Lchild,n);
         GetNum(tree->Rchild,n);
     }
     else
     return ;
 }
int main()
{
    struct Tree * tree;
    tree=CreateTree(tree);
    ListTree(tree);
    int num=0;
    GetNum(tree,num);
    printf("叶子节点的个数为:");
    printf("%d",num);
}

 

posted @ 2018-01-02 10:14  Hztiger  阅读(529)  评论(0编辑  收藏  举报