二叉树的实现
树的节点通过定义BinTreeNode结构体来实现,二叉树则由BinaryTree类实现。
BinTree.h 头文件
//BinTree.h
#include<iostream>
#include<queue>
using namespace std;
struct BinNode
{
char data;
BinNode *leftChild, *rightChild;
};
class BinTree
{
private:
BinNode *root;
char stopValue, nullValue;
public:
BinTree();
BinNode* getRoot();
void preOrder(BinNode *node);
void inOrder(BinNode *node);
void postOrder(BinNode *node);
void levelOrder(BinNode *node);
int NodeNum(BinNode *node);
int TreeDepth(BinNode *node);
int LeafNum(BinNode *node);
BinNode* Create();
};
BinTree::BinTree()
{
root = new BinNode;
nullValue = '#';
root = Create();
}
BinNode* BinTree::Create()
{
char ch;
cin >> ch;
BinNode *pnode;
if(ch == '#')
pnode = NULL;
else
{
pnode = new BinNode;
pnode->leftChild = Create();
pnode->data = ch;
pnode->rightChild = Create();
}
return pnode;
}
BinNode* BinTree::getRoot()
{
return root;
}
void BinTree::preOrder(BinNode *node)
{
if(!node)
return ;
cout << node->data << ' ';
preOrder(node->leftChild);
preOrder(node->rightChild);
}
void BinTree::inOrder(BinNode *node)
{
if(!node)
return ;
inOrder(node->leftChild) ;
cout << node->data << ' ';
inOrder(node->rightChild);
}
void BinTree::postOrder(BinNode *node)
{
if(!node)
return ;
postOrder(node->leftChild);
postOrder(node->rightChild);
cout << node->data << ' ';
}
void BinTree::levelOrder(BinNode *node)
{
queue<BinNode *> q;
BinNode *s = node;
if(!s)
return ;
q.push(s);
while(!q.empty())
{
s = q.front();
q.pop();
cout << s->data << ' ';
if(s->leftChild)
q.push(s->leftChild);
if(s->rightChild)
q.push(s->rightChild);
}
}
int BinTree::LeafNum(BinNode *node)
{
if(!node)
return 0;
if(!node->leftChild && !node->rightChild)
return 1;
return LeafNum(node->leftChild) + LeafNum(node->rightChild);
}
int BinTree::NodeNum(BinNode *node)
{
if(!node)
return 0;
return 1 + NodeNum(node->leftChild) + NodeNum(node->rightChild);
}
int BinTree::TreeDepth(BinNode *node)
{
if(!node)
return 0;
int ldepth=TreeDepth(node->leftChild);
int rdepth=TreeDepth(node->rightChild);
return max(ldepth, rdepth)+1;
}
测试程序main.cpp
//main.cpp
#include<iostream>
#include"BinTree.h"
using namespace std;
int main()
{
BinTree a;
cout<<"preorder:";
a.preOrder(a.getRoot());
cout<<endl;
cout<<"inorder:";
a.inOrder(a.getRoot());
cout<<endl;
cout<<"postorder:";
a.postOrder(a.getRoot());
cout<<endl;
cout<<"leafnum:"<<a.LeafNum(a.getRoot());
cout<<endl;
cout<<"nodenum:"<<a.NodeNum(a.getRoot());
cout<<endl;
cout<<"treedepth:"<<a.TreeDepth(a.getRoot());
cout<<endl;
return 0;
}
/*
A
B C
D E F G
# # # # # # # #
*/
//ABD##E##CF##G##(先序建树)