您的位置:首页 > 编程语言 > C语言/C++

C++ 二叉树实现 创建,先序遍历,中序遍历,后序遍历

2013-04-28 21:49 851 查看
#ifndef _BTREE_H_
#define _BTREE_H_

#include <iostream>
using namespace std;
struct BTNode
{
BTNode *left_child;
BTNode *right_child;
int data;
BTNode(int val,BTNode* left=NULL,BTNode* right=NULL)
{
data=val;
left_child=left;
right_child=right;
}
};
class Btree
{
public:
Btree(){m_troot=NULL;m_tsize=0;}
~Btree();
void CreateTree(int *treelist,int length);
void PreOrder();
void InOrder();
void PostOrder();
int NodeCount();
private:
void preorder(BTNode* node);
void inorder(BTNode* node);
void postorder(BTNode* node);
void destroy(BTNode* node);
BTNode* m_troot;
int m_tsize;
};
void Btree::CreateTree(int *treelist,int length)
{
if(m_troot==NULL)
{
m_troot=new BTNode(treelist[0]);
if(m_troot==NULL)
return;
++m_tsize;
}
for(int i=1;i<length;i++)
{
BTNode* tmp_node=m_troot;
BTNode* reserve=NULL;
while(tmp_node!=NULL)
{
reserve=tmp_node;//保存找到的那个插入位置
if(treelist[i]<tmp_node->data)//按照data大小进行插入,左子小于双亲,右子大于双亲
{
tmp_node=tmp_node->left_child;
}
else
{
tmp_node=tmp_node->right_child;
}
}
BTNode* new_node=new BTNode(treelist[i]);
if(new_node==NULL)
return;
++m_tsize;
if(treelist[i]<reserve->data)
reserve->left_child=new_node;
else
reserve->right_child=new_node;
}
}
int Btree::NodeCount()
{
return m_tsize;
}
void Btree::preorder(BTNode* node)
{
if(node!=NULL)
{
cout<<node->data<<" ";
preorder(node->left_child);
preorder(node->right_child);
}
}
void Btree::inorder(BTNode* node)
{
if(node!=NULL)
{
inorder(node->left_child);
cout<<node->data<<" ";
inorder(node->right_child);
}
}
void Btree::postorder(BTNode* node)
{
if(node!=NULL)
{
postorder(node->left_child);
postorder(node->right_child);
cout<<node->data<<" ";
}
}
void Btree::destroy(BTNode *node)
{
if(node!=NULL)
{
destroy(node->left_child);
destroy(node->right_child);
//cout<<"销毁第"<<m_tsize--<<"个数据为"<<node->data<<"的节点"<<endl; //用于测试
delete node;
node=NULL;
}
}
Btree::~Btree()
{
//cout<<"------------析构函数------------\n";//用于测试
destroy(m_troot);
m_troot=NULL;
m_tsize=0;
//system("pause");//用于测试
}
void Btree::PreOrder()
{
preorder(m_troot);
cout<<"\n";
}
void Btree::InOrder()
{
inorder(m_troot);
cout<<"\n";
}
void Btree::PostOrder()
{
postorder(m_troot);
cout<<"\n";
}
#endif
int main()
{
int array[]={32,55,11,67,7,24,77,5,15,10};
int k=sizeof(array)/sizeof(array[0]);
Btree btree;
btree.CreateTree(array,k);
printf("---------节点个数--------------\n");
printf("%d\n",btree.NodeCount());
printf("---------先序遍历结果----------\n");
btree.PreOrder();
printf("---------中序遍历结果----------\n");
btree.InOrder();
printf("---------后序遍历结果----------\n");
btree.PostOrder();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐