结训赛第一次复习:二叉树的基本操作(一)

二叉树的基本操作包括了构建,遍历(先序,中序,后序),统计节点数,统计叶子数,统计层数等问题

其中构建又分为已知先序求中序和后序

什么是先序,中序,后序可以参考以下文章:

https://blog.csdn.net/qq_33243189/article/details/80222629

题目:

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/3341+先序遍历

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node*l,*r;
};
char s[60];
int ans;
struct node*creat()
{
    struct node*root;
    char c;
    c=s[ans++];
    if(c==',')
        root=NULL;
    else
    {
        root=(struct node*)malloc(sizeof(struct node));
        root->data=c;
        root->l=creat();
        root->r=creat();
    }
    return root;

}

//void beorder(struct node*root)求先序

//{
    //if(root)
   // {
       // inorder(root->l);
       // printf("%c",root->data);
       // inorder(root->r);
    //}
//}
void inorder(struct node*root)//求中序
{
    if(root)
    {
        inorder(root->l);
        printf("%c",root->data);
        inorder(root->r);
    }
}
void aforder(struct node*root)//求后序
{
    if(root)
    {
        aforder(root->l);
        aforder(root->r);
        printf("%c",root->data);
    }
}
int main()
{
    while(scanf("%s",s)!=EOF)
    {
        struct node*root;
        ans=0;
        root=creat();
        inorder(root);
        printf("\n");
        aforder(root);
        printf("\n");
    }
    return 0;
}

又可以有已知后序中序求先序只要把握住根在哪即可:

扫描二维码关注公众号,回复: 12164796 查看本文章

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/1489

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    int data;
    struct node*l,*r;
};
char str[100000];
char str1[100000];
struct node*rebuild(char str[],char str1[],int n)
{
    struct node*root;
    int i;
    if(n<=0)//需要判断不存在的时候
        return NULL;
    root=(struct node*)malloc(sizeof(struct node));
    root->data=str[0];
    for(i=0;i<=n-1;i++)
    {
        if(str1[i]==str[0])
            break;
    }
    root->l=rebuild(str+1,str1,i);
    root->r=rebuild(str+i+1,str1+i+1,n-i-1);
    return root;
}
void aforder(struct node*root)
{
    if(root)
    {
       aforder(root->l);
       aforder(root->r);
       printf("%c",root->data);
    }
}
int main()
{
    int n;
    struct node*root;
    scanf("%s",str);
    scanf("%s",str1);
    n=strlen(str);
    root=rebuild(str,str1,n);
    aforder(root);
    printf("\n");
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/weixin_44067773/article/details/87866973
今日推荐