附件
TIM截图20190516150201.png

#include<iostream>
#include<cstdlib>
using namespace std;

#define ElemType char

struct MyStruct
{
    ElemType data;
    MyStruct* left;
    MyStruct* right;
};
void creat(MyStruct* &tree)//建立二叉树
{
    MyStruct* k;
    char c;
    cin >> c;
    if (c != '#')//如果不为'#'则放入
    {
        tree = (MyStruct*)malloc(sizeof(MyStruct));
        tree->data = c;
        creat(tree->left);//左递归
        creat(tree->right);//右递归
    }
    else//为’#’说明结束,置空
    {
        tree = NULL;
    }
}
void pre(MyStruct* tree)//先序输出
{
    if (tree)
    {
        cout << tree->data << " ";
        pre(tree->left);
        pre(tree->right);

    }
}
void mid(MyStruct* tree)//中序输出
{
    if (tree)
    {
        mid(tree->left);
        cout << tree->data << " ";
        mid(tree->right);

    }
}
void last(MyStruct* tree)//后序输出
{
    if (tree)
    {
        last(tree->left);
        last(tree->right);
        cout << tree->data << " ";
    }
}
int treecnt(MyStruct* tree)
{
    int cnt;
    if(tree==NULL)
        return 0;
    if(tree->left==NULL&&tree->right==NULL)
        return 1;
    cnt=treecnt(tree->left)+treecnt(tree->right);
}
int treedeep(MyStruct* tree)
{
    int m,n;
    if(tree==NULL)
        return 0;
    else
    {
        m=treedeep(tree->left);
        n=treedeep(tree->right);
        if(m>n)
            return (m+1);
        else
            return (n+1);
    }
}
int main()
{
    MyStruct *tree;
    cout<<"以#代替当前为空的节点,以先序建立二叉树"<<endl;
    creat(tree);
    cout << "创建完成" << endl;
    cout << "前序遍历" << endl;
    pre(tree);
    cout << endl;
    cout << "中序遍历" << endl;
    mid(tree);
    cout << endl;
    cout << "后序遍历" << endl;
    last(tree);
    cout << endl;
    int cnt=treecnt(tree);
    cout<<"叶子节点数的个数为"<<cnt<<endl;
    int deep=treedeep(tree);
    cout<<"树的深度为"<<deep<<endl;
    cout << "结束" << endl;
    system("pause");
    return 0;

}
最后修改:2019 年 05 月 26 日 02 : 42 PM