I - 二叉树

Description

已知二叉树的一个按前序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树,并输出建立二叉树的前序遍历序列、中序遍历序列、后序遍历序列、层次遍历序列、深度、叶子数。

Input

多组测试数据,对于每组测试数据,输入一个长度小于50的按前序遍历输入的字符序列。

Output

对于每组测试数据,第1行输出其前序遍历序列、第2行输出其中序遍历序列、第3行输出其后序遍历序列、第4行输出其深度、第5行输出其叶子数。

Sample

Input 

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

Output 

abcdegf
cbegdfa
cgefdba
abcdefg
5
3
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
   int data;
   struct node*left;
   struct node*right;
}tree;
char str[55];
int flag=0;
tree*creat(tree*root)
{
    if(str[flag]==',')
    {
       flag++;
       return NULL;
    }
    else
    {
       root=(tree*)malloc(sizeof(tree));
       root->data=str[flag++];
       root->left=creat(root->left);
       root->right=creat(root->right);
    }
    return root;
}
void first(tree*root)
{
    if(root!=NULL)
    {
        printf("%c",root->data);
        first(root->left);
        first(root->right);
    }
}
void mid(tree*root)
{
    if(root!=NULL)
    {
        mid(root->left);
        printf("%c",root->data);
        mid(root->right);
    }
}
void last(tree*root)
{
    if(root!=NULL)
    {
        last(root->left);
        last(root->right);
        printf("%c",root->data);
    }
}
void levelOrder(tree*root)
{
    tree*p[55];
    int in,out;
    in=out=0;
    p[in++]=root;
    while(in>out)
    {
        if(p[out])
        {
           printf("%c",p[out]->data);
           p[in++]=p[out]->left;
           p[in++]=p[out]->right;
        }
        out++;
    }

}
int deep(tree*root)
{
    if(root==NULL)
    {
        return 0;
    }
    else
    {
        return max(deep(root->left)+1,deep(root->right)+1);
    }

}
int coutlevel(tree*root)
{
   if(root==NULL)
   {
      return 0;
   }
   if(root->left==NULL&&root->right==NULL)
   {
      return 1;
   }
   return coutlevel(root->left)+coutlevel(root->right);
}
int main()
{
    tree*root;
    while(~scanf("%s",str))
    {
       flag=0;
       root=creat(root);
       first(root);
       printf("\n");
       mid(root);
       printf("\n");
       last(root);
       printf("\n");
       levelOrder(root);
       printf("\n");
       printf("%d\n",deep(root));
       printf("%d\n",coutlevel(root));
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值