二叉树的基本操作

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

typedef char BTDataType;
struct BinaryTreeNode
{
    BinaryTreeNode* left;
    BinaryTreeNode* right;
    BTDataType data;
};
typedef BinaryTreeNode BTNode;

void PrevOrder(BTNode* root)//前序遍历
{
    if (root == nullptr)
    {
        cout << "NULL" << " ";
        return;
    }

    cout << root->data << " ";
    PrevOrder(root->left);
    PrevOrder(root->right);
}

void InOrder(BTNode* root)//中序遍历
{
    if (root == nullptr)
    {
        cout << "NULL" << " ";
        return;
    }
    InOrder(root->left);
    cout << root->data << " ";
    InOrder(root->right);
}

void PostOrder(BTNode* root)//后序遍历
{
    if (root == nullptr)
    {
        cout << "NULL" << " ";
        return;
    }
    PostOrder(root->left);
    PostOrder(root->right);
    

    cout << root->data << " ";
}

int TreeSize(BTNode* root)//树的结点个数
{
    return root == nullptr ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}

int TreeLeafSize(BTNode* root)//树的叶子结点个数
{
    if (root == nullptr)
        return 0;

    if (root->left == nullptr && root->right == nullptr)
        return 1;

    return TreeLeafSize(root->left) + TreeLeafSize(root->right);
}

void LevelOrder(BTNode* root)//层序遍历
{
    queue<BTNode*>q;
    if (root)
        q.push(root);

    while (!q.empty())
    {
        BTNode* front = q.front();
        q.pop();
        cout << front->data << " ";

        if (front->left)
        {
            q.push(front->left);
        }

        if (front->right)
        {
            q.push(front->right);
        }
    }

    cout << endl;
    
    while (!q.empty())
    {
        q.pop();
    }

}

int main()
{
    BTNode* A = new BTNode;
    A->data = 'A';
    A->left = nullptr;
    A->right = nullptr;

    BTNode* B = new BTNode;
    B->data = 'B';
    B->left = nullptr;
    B->right = nullptr;

    BTNode* C = new BTNode;
    C->data = 'C';
    C->left = nullptr;
    C->right = nullptr;

    BTNode* D = new BTNode;
    D->data = 'D';
    D->left = nullptr;
    D->right = nullptr;

    BTNode* E = new BTNode;
    E->data = 'E';
    E->left = nullptr;
    E->right = nullptr;

    A->left = B;
    A->right = C;

    B->left = D;
    B->right = E;

    PrevOrder(A);
    cout << endl;
    InOrder(A);
    cout << endl;
    PostOrder(A);
    cout << endl;

    cout << TreeSize(A) << endl;
    cout << TreeSize(B) << endl;
    cout << TreeSize(C) << endl;
    cout << TreeLeafSize(C) << endl;

    LevelOrder(A);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值