SDUT 2136 数据结构实验之二叉树的建立与遍历

 

数据结构实验之二叉树的建立与遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

       已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。

Input

 输入一个长度小于50个字符的字符串。

Output

输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。

Sample Input

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

Sample Output

cbegdfa
cgefdba
3
5

提示:本题是要根据前序遍历和空节点来构造二叉树,从而输出其中序遍历和后序遍历,以及叶子结点个数与二叉树深度,
   叶子结点可以根据树中有多少没有子结点的点求出个数,深度就是找左右子树的深度的较大值加上根节点算一个深度一直递归到头。

代码实现如下(gcc):
#include <stdio.h>
#include <stdlib.h>

char a[55];
int i,sum=0;

typedef struct node
{
    char data;
    struct node *left;
    struct node *right;
} node;

node *create()
{
    node *root;
    if(a[i]==',')
    {
        i++;
        root=NULL;
    }
    else
    {
        root=(node *)malloc(sizeof(struct node));
        root->data=a[i++];
        root->left=create();
        root->right=create();
    }
    return root;
}

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

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

void get_yz(node *root)//叶子结点个事
{
    if(root)
    {
        if((!root->left)&&(!root->right))//如果存在没有左右结点的点,计数+1
        {
            sum++;
        }
        get_yz(root->left);
        get_yz(root->right);//递归遍历
    }
}

int get_height(node *root)
{
    if(root==NULL)
    {
        return 0;
    }
    else
    {
        int h1=get_height(root->left);//左子树深度
        int h2=get_height(root->right);//右子树深度
        int max;
        max=h1;
        if(h2>max)
        {
            max=h2;
        }
        return max+1;
    }
}

int main()
{
    i=0;
    int h;
    scanf("%s",a);
    node *root;
    root=create();
    isort(root);
    printf("
");
    psort(root);
    printf("
");
    get_yz(root);
    printf("%d
",sum);
    h=get_height(root);
    printf("%d
",h);
    return 0;
}


/***************************************************
Result: Accepted
Take time: 0ms
Take Memory: 160KB
****************************************************/
原文地址:https://www.cnblogs.com/jkxsz2333/p/9498683.html