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

来源:互联网 发布:快看漫画mac 编辑:程序博客网 时间:2024/06/02 01:13

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

cbegdfacgefdba35

提示

#include<bits/stdc++.h>
using namespace std;
struct node
{
    char data;
    struct node *l;
    struct node *r;
};
string s;
int i;
struct node *creat()
{
    struct node *root;
    if(s[i++]==',')
        root=NULL;
    else
    {
        root=new node;
        root->data=s[i-1];
        root->l=creat();
        root->r=creat();
    }
    return root;
};
void middle(struct node *root)
{
    if(root)
    {
        middle(root->l);
        cout<<root->data;
        middle(root->r);
    }
}
int num;
void leavelnum(struct node *root)
{
    queue<struct node *>q1;
    if(root)
        q1.push(root);
    while(!q1.empty())
    {
        root=q1.front();
        if(!root->l&&!root->r)
        {
            num++;
        }
        q1.pop();
        if(root->l)
            q1.push(root->l);
        if(root->r)
            q1.push(root->r);
    }
}
void last(struct node *root)
{
    if(root)
    {
        last(root->l);
        last(root->r);
        cout<<root->data;
    }
}
int depth(struct node *root)
{
    if(root)
    {
        int l=depth(root->l);
        int r=depth(root->r);
        if(l>r)
            return l+1;
        else
            return r+1;
    }
    else
        return 0;
}
int main()
{
    while(cin>>s)
    {
        i=0;
        num=0;
        struct node *root;
        root=creat();
        middle(root);
        cout<<endl;
        last(root);
        cout<<endl;
        leavelnum(root);
        cout<<num<<endl;
        cout<<depth(root)<<endl;
    }
    return 0;
}

0 0