这个二叉树的建立过程中,要求手动输入一个一个的数据,不过你可以选择输入或不输入左右子树。
至于遍历的方法也就是那基本的三种:先序遍历,中序遍历,后序遍历(还有一种线索遍历比较复杂,这里不给出);
#include<iostream>
using namespace std;
typedef int DATATYPE;
//定义 一个树结点的结构体
struct treeNode
{
DATATYPE data;
struct treeNode* leftNode;
struct treeNode* rightNode;
};
typedef struct treeNode* pNode;
//初始化一个树结点
bool initNode(pNode &node)
{
DATATYPE data;
if(!(node = (pNode)malloc(sizeof(pNode)))) return false;
cin>>data;
node->data = data;
node->leftNode = NULL;
node->rightNode = NULL;
return true;
}
//创建一个树
void create(pNode &root) //注意这里面一定要用“引用”
{
char flag;
printf("Please input the data:");
if(initNode(root))
{
//由用户自己决定是否加入左子树的数据
cout<<"Input node "<<root->data<<"'s left child's data?(y/n):";
getchar();
scanf("%c",&flag);
getchar();
if(flag == 'y' || flag == 'Y')
{
create(root->leftNode);
}
//由用户自己决定是否加入右子树的数据
cout<<"Input node "<<root->data<<"'s right child's data?(y/n):";
scanf("%c",&flag);
getchar();
if(flag == 'y' || flag == 'Y')
{
create(root->rightNode);
}
}
}
//先序遍历
void preOrderView(pNode &root)
{
//如果为空,则不管了
if(root == NULL) return;
//输出数据
cout<<root->data<<endl;
//先序遍历左子树
preOrderView(root->leftNode);
//先序遍历右子树
preOrderView(root->rightNode);
}
//中序遍历
void cenOrderView(pNode &root)
{
//如果为空,则不管了
if(root == NULL) return;
//中序遍历左子树
cenOrderView(root->leftNode);
//输出数据
cout<<root->data<<endl;
//中序遍历右子树
cenOrderView(root->rightNode);
}
//后序遍历
void aftOrderView(pNode &root)
{
//如果为空,则不管了
if(root == NULL) return;
//后序遍历左子树
aftOrderView(root->leftNode);
//后序遍历右子树
aftOrderView(root->rightNode);
//输出数据
cout<<root->data<<endl;
}
//main主函数
int main()
{
pNode tree = NULL;
create(tree);
//输出先序遍历的结果
printf("The preOrderView result:/n");
preOrderView(tree);
//输出中序遍历的结果
printf("The cenOrderView result:/n");
cenOrderView(tree);
//输出后序遍历的结果
printf("The aftOrderView result:/n");
aftOrderView(tree);
return 0;
}