The first review of the finale: the basic operation of the binary tree (1)

The basic operations of a binary tree include construction, traversal (pre-order, middle-order, post-order), count the number of nodes, count the number of leaves, count the number of layers, etc.

Among them, the construction is divided into known first order and middle order and post order

What is the first order, middle order, and second order can refer to the following articles:

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

topic:

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/3341 + pre-order traversal

#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) seek first order

//{
    //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;
}

There can also be known post-order, middle-order and first-order as long as the root is grasped:

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

Guess you like

Origin blog.csdn.net/weixin_44067773/article/details/87866973