二叉树的构造与遍历

来源:互联网 发布:海贼王 居鲁士 知乎 编辑:程序博客网 时间:2024/06/05 05:31
#include<bits/stdc++.h>/*  构造链式二叉树     输出先序遍历 中序遍历 后序遍历结果    统计叶子节点的个数和二叉树的深度*/struct Tree{    char data;    struct Tree *lchild, *rchild;}*t;int cnt=0;//用于统计叶子的数目struct Tree *creat(struct Tree *t)//根据先序建立二叉树{    char ch;    ch = getchar();    if(ch=='#') t = NULL;    else{        t = (struct Tree *)malloc(sizeof(struct Tree));        t->data = ch;        t->lchild= creat(t->lchild);        t->rchild= creat(t->rchild);    }    return t;}void Preorder(struct Tree *t)//先序遍历{    if(t!=NULL){        printf("%c",t->data);        Preorder(t->lchild);        Preorder(t->rchild);    }}void Inorder(struct Tree *t)//中序遍历{    if(t!=NULL){        Inorder(t->lchild);        printf("%c", t->data);        Inorder(t->rchild);    }}void Postorder(struct Tree *t)//后续遍历{    if(t!=NULL){        Postorder(t->lchild);        Postorder(t->rchild);        printf("%c", t->data);    }}void leaf(struct Tree *t)//求叶子节点数目{    if(t){        if((t->lchild==NULL) && (t->rchild==NULL)) cnt++;        leaf(t->lchild);        leaf(t->rchild);    }}int deep(struct Tree *t)// 求二叉树深度{    int l, r;    if(!t) return 0;    l = deep(t->lchild);    r = deep(t->rchild);    return l>r?l+1:r+1;}int main(){    struct Tree *root;    printf("输入先序序列构造二叉树:");    root = creat(root);    printf("先序遍历:");    Preorder(root);    printf("\n");    printf("中序遍历:");    Inorder(root);    printf("\n");    printf("后序遍历:");    Postorder(root);    printf("\n");    leaf(root);    printf("叶子节点个数:%d\n", cnt);    printf("深度:%d\n", deep(root));    return 0;}


测试数据:ABC##DE#G##F####


原创粉丝点击