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");
}