【C++数据结构】二叉树

BTree.h

#pragma once

class CNode
{
public:
    int data;
    CNode *lNode;
    CNode *rNode;
public:
    CNode();
    ~CNode();
};

class CBTree
{
public:
    CBTree();
    ~CBTree();
public:
    CNode *head;

public:
    void Insert(CNode*&,int);
    int ColumnCount(CNode*);
    int LeafCount(CNode*);

public:
    void PreOrder(CNode*);
    void MidOrder(CNode*);
    void PosOrder(CNode*);
};

BTree.cpp

#include "BTree.h"
#include <iostream>
CNode::CNode()
{
}

CNode::~CNode()
{

}



CBTree::CBTree()
{
}


CBTree::~CBTree()
{
}

void CBTree::Insert(CNode *&node, int data)
{
    if (node == nullptr)
    {
        node = new CNode;
        node->data = data;
        return;
    }
    if (node->data >= data)
    {
        Insert(node->lNode, data);
    }
    else
    {
        Insert(node->rNode,data);
    }
}

int CBTree::ColumnCount(CNode *node)
{
    static int count = 0;
    if (node == nullptr)
    {
        return count;
    }   
    count++;
    ColumnCount(node->lNode);
    ColumnCount(node->rNode);
}

int CBTree::LeafCount(CNode *node)
{
    static int count = 0;
    if (node == nullptr)
    {

        return count;
    }

    if (node->lNode == nullptr&&node->rNode == nullptr)
    {
        count++;
    }

    LeafCount(node->lNode);
    LeafCount(node->rNode);
}


void CBTree::PreOrder(CNode *node)
{
    if (node == nullptr)
    {
        return;
    }
    std::cout << node->data << std::endl;
    PreOrder(node->lNode);
    PreOrder(node->rNode);
}

void CBTree::MidOrder(CNode *node)
{
    if (node == nullptr)
    {
        return;
    }
    PreOrder(node->lNode);
    std::cout << node->data << std::endl;
    PreOrder(node->rNode);
}

void CBTree::PosOrder(CNode *node)
{
    if (node == nullptr)
    {
        return;
    }
    PreOrder(node->lNode);
    PreOrder(node->rNode);
    std::cout << node->data << std::endl;
}

main.cpp

void main()
{
    CBTree t;
    for (int index = 0; index < 3; index++)
    {
        t.Insert(t.head, rand()%50);
    }
    std::cout << "PreOrder" << std::endl;
    t.PreOrder(t.head);
    std::cout << std::endl;
    std::cout << "MidOrder" << std::endl;
    t.MidOrder(t.head);
    std::cout << std::endl;
    std::cout << "PosOrder" << std::endl;
    t.PosOrder(t.head);
    std::cout << "Count:" << t.ColumnCount(t.head) << std::endl;
    std::cout << "LeafCount:" << t.LeafCount(t.head) << std::endl;
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值