数据结构

二叉树的基本操作

2020-08-06  本文已影响0人  往sir_b2a2
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node //树节点定义
{
    char data;
    struct node* left;//指向左子树
    struct node* right;//指向右子树
}BTN, * BT;
void create(BT& t)//先序创建二叉树
{
    char c;
    cin >> c;
    if ('#' == c)
        t = NULL;
    else
    {
        t = new BTN;
        t->data = c;
        create(t->left);
        create(t->right);
    }
}
void xian(BT &t)//先序遍历
{
    if (t)
    {
        cout << t->data;
        xian(t->left);
        xian(t->right);
    }
}
void zhong(BT &t)//中序遍历
{
    if (t)
    {
        zhong(t->left);
        cout << t->data;
        zhong(t->right);
    }
}
void hou(BT &t)
{
    if (t)
    {
        hou(t->left);
        hou(t->right);
        cout << t->data;
    }
}
//其实会发现cout在前/中/后,正好先/中/后序遍历
void copy(BT &t, BT& new_t)//复制二叉树
{
    if (t)
    {
        new_t = new BTN;
        new_t->data = t->data;
        copy(t->left, new_t->left);
        copy(t->right, new_t->right);
    }
    else
    {
        new_t = NULL;
        return;
    }
}
int depth(BT &t)//计算二叉树的深度
{
    if (t)
    {
        int m = depth(t->left);
        int n = depth(t->right);
        if (m > n)
            return m + 1;
        else
            return n + 1;
    }
    else
    {
        return 0;
    }
}
int nodecount(BT &t)//统计二叉树的节点个数
{
    if (t)
        return nodecount(t->left) + nodecount(t->right) + 1;
    else
        return 0;
}
int leafcount(BT t)//统计树叶节点个数
{//下面的if语句体顺序不能弄反
    if (!t)
        return 0;
    else if (!t->left && !t->right)//若左右子树为空
        return 1;
    else
        return leafcount(t->left) + leafcount(t->right);
}
int main()
{
    BT t;
    cout << "先序创建一个二叉树:";
    create(t);//输入例子AB#CD##E##F#GH###

    cout << "先序遍历:" ;
    xian(t);
    cout << endl;

    cout << "中序遍历:";
    zhong(t);
    cout << endl;

    cout << "后序遍历:" ;
    hou(t);
    cout << endl;

    cout << "二叉树的深度:"<<depth(t)<<endl;
    cout << "二叉树的节点个数:" << nodecount(t) << endl;
    cout << "二叉树的树叶节点个数:" << leafcount(t) << endl;


    cout <<endl<< "复制二叉树:" << endl;
    BT new_t;
    copy(t, new_t);
    cout << "先序遍历:";
    xian(new_t);
    cout << endl;

    cout << "中序遍历:";
    zhong(new_t);
    cout << endl;

    cout << "后序遍历:";
    hou(new_t);
    cout << endl;

    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读