您的位置:首页 > 理论基础 > 数据结构算法

一个简单的数据结构举例——二叉树及…

2015-05-30 23:47 453 查看
链接地址:BinaryTree

//头文件名:BTree.h

#include "stdafx.h"
#include "iostream"
using namespace std;
class BTree
{
public :
int data;
BTree *left;
BTree *right;
BTree(int);
BTree();
};

//cpp名:BTree.cpp

#include "stdafx.h"
#include "BTree.h"

BTree::BTree(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}

BTree::BTree()
{
this->data = NULL;
this->left = NULL;
this->right = NULL;
}

// BinaryTree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "BTree.h"
#include "ctime"

void Insert(BTree*,BTree*);
void Display(BTree *head);
void FirstDisplay(BTree *p);
void LastDisplay(BTree *head);
BTree *node=NULL;

int _tmain(int argc, _TCHAR* argv[])
{
int x, y;
while (1)
{
node = NULL;
cout << "1:随机产生结点" << endl
<< "2:自定义结点(以-99999为结束)" << endl;
cin >> x;
if (1==x || 2==x)
{
switch (x)
{
case 1:goto f1; break;
case 2:goto f2; break;
}
f1:
{
srand(unsigned(time(NULL)));
cout << "产生多少个结点:";
cin >> x;
for (int i = 0; i < x; i++)
{
y = rand() % 100 - rand() % 100;
cout << y << " ";
Insert(node, new BTree(y));
}
cout << endl << endl << "前序遍历结果:";
FirstDisplay(node);
cout << endl << endl << "中序遍历结果:";
Display(node);
cout << endl << endl << "后序遍历结果:";
LastDisplay(node);
cout << endl << endl;
continue;
}
f2:
{ while (cin >> x && x!= -99999)
{
Insert(node, new BTree(x));
}
cout << endl << endl << "前序遍历结果:";
FirstDisplay(node);
cout << endl << endl << "中序遍历结果:";
Display(node);
cout << endl << endl << "后序遍历结果:";
LastDisplay(node);
cout << endl<<endl;
}
}
else continue;
}
return 0;
}

void Insert(BTree *father,BTree *son)
{
if (NULL == father)
{
node = son;
return;
}
if (father->data > son->data)
{
if (father->left != NULL)
{
Insert(father->left, son);
}
else
{
father->left = son;
}
}
else if (father->data < son->data)
{
if (father->right != NULL)
{
Insert(father->right, son);
}
else
{
father->right = son;
}

}
else
{
if (!father->left)
father->left = son;
else if (!father->right)
father->right = son;
else
Insert(father->left, son);
}
}

//中序遍历
void Display(BTree *p)
{
if (p->left)
Display(p->left);
cout << p->data << " ";
if (p->right)
Display(p->right);
else return;
}

//前序遍历
void FirstDisplay(BTree *p)
{
cout << p->data << " ";
if (p->left)
FirstDisplay(p->left);
if (p->right)
FirstDisplay(p->right);
else return;
}

//后序遍历
void LastDisplay(BTree *p)
{
if (p->left)
LastDisplay(p->left);
if (p->right)
LastDisplay(p->right);
cout << p->data << " ";
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: