二叉树--基本知识点

数据结构实验之二叉树二:遍历二叉树

Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。

 

Sample Input

abc,,de,g,,f,,,

Sample Output

cbegdfa
cgefdba
1、按先序遍历输入的字符序列:
struct node * creat()
{
    char ch = s[l++];
    struct node *root;
    if(ch==',')
    {
        return NULL;
    }
    else
    {
        root = (struct node *)malloc(sizeof(struct node));
        root->data = ch;
        root->left = creat();
        root->right = creat();
    }
    return root;
}
2.已知前序遍历和中序遍历,求二叉树。
struct node * creat(char *st1, char *st2, int n)
{
    if(n<=0) return NULL;
    struct node *root;
    root = (struct node *)malloc(sizeof(struct node));
    root->data = st1[0];
    char *i;
    for(i=st2; i<st2+n; i++)
    {
        if(*i==*st1)
            break;
    }
    int x = i-st2+1;
    root->left = creat(st1+1, st2, x-1);
    root->right = creat(st1+x, st2+x, n-x);
    return root;
}
3.已知中序遍历和后序遍历,求二叉树。
struct node *creat(char *st1, char *st2, int n)
{
    if(n<=0)
        return NULL;
    struct node *root;
    root = (struct node *)malloc(sizeof(struct node));
    root->data = *(st2+n-1);
    char *i;

    for(i=st1; i<st1+n; i++)
    {
        if(*i==*(st2+n-1))
        {
            break;
        }
    }
    int x = i-st1+1;
    root->left  = creat(st1, st2, x-1);
    root->right = creat(st1+x, st2+x-1, n-x);
    return root;
}
4.层次遍历:
void level(struct node *root)
{
    struct node *a[60];
    int x = 0;
    int y = 1;
    a[0] = root;
    while(x<y)
    {
        if(a[x])
        {
            printf("%c", a[x]->data);
            a[y++] = a[x]->left;
            a[y++] = a[x]->right;
        }
        x++;
    }
}
5、求二叉树的高度
int deep(struct node *root)
{
    if(root==NULL)    return 0;
    if(root->left==NULL && root->right==NULL) return 1;
    int ld = deep(root->left);
    int rd = deep(root->right);
    if(ld>rd) return 1+ld;
    else if(ld<=rd) return 1+rd;
}
6、求叶子数。
int leaf(struct node *root)
{
    if(root==NULL) return 0;
    if(root->left == NULL && root->right == NULL)
        return 1;
    else
        return leaf(root->left)+leaf(root->right);
}
7、按从上到下从左到右的顺序输出二叉树的叶子结点。
void leaf(struct node *root)
{
    struct node *a[N];
    int x = 0;
    int y = 1;
    a[0] = root;
    while(x<y)
    {
        if(a[x])
        {
            if(a[x]->left==NULL && a[x]->right==NULL)
                printf("%c", a[x]->data);
            a[y++] = a[x]->left;
            a[y++] = a[x]->right;
        }
        x++;
    }
}
8、后序输出:

void after(struct node *root)
{
    if(root)
    {
        after(root->left);
        after(root->right);
        printf("%c", root->data);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/81433996