二叉树的基本操作 题目编号:462
设计二叉树类,能够对二叉树进行先序、中序、后序和层序遍历,遍历的操作为输出结点的值,设计主函数,输入一棵二叉树,按先序、中序、后序、层序的遍历顺序输出结点的值。二叉树的结点数不超过20。
输入描述
输入数据只有一组, 二叉树的结点均为一个数字, 数据为0代表当前结点为空。输入结点的值按照二叉树的先序遍历顺序, 比如输入:
1 2 4 0 0 5 0 0 3 0 6 0 0 ,0表示空,输入的数字之间由空格分隔。上述输入对应的二叉树如下图所示:
输出描述
输出先序、中序、后序和层序遍历二叉树得到的序列,各占一行,同一行的数字之间由空格分隔。
输入样例
1 2 4 0 0 5 0 0 3 0 6 0 0
输出样例
1 2 4 5 3 6
4 2 5 1 3 6
4 5 2 6 3 1
1 2 3 4 5 6
#include<iostream>
using namespace std;
static int count=0;
struct Node
{
char data;
Node *Lchild,*Rchild,*next;
};
//struct Node2
//{
// char data;
// Node *next;
//};
class BiTree
{
public:
BiTree(){root=Create(root);}
~BiTree(){Release(root);}
void qian(){qian(root);}
void zhong(){zhong(root);}
void hou(){hou(root);}
void ceng(){ceng(root);};
private:
Node *root,*q;
Node *Create(Node *bt);
void Release(Node *bt);
void qian(Node *bt);
void zhong(Node *bt);
void hou(Node *bt);
void ceng(Node *bt);
int rear,front;
char data[100];
};
Node*BiTree::Create(Node *bt)
{
char s;
cin>>s;
if(s=='0')
bt=NULL;
else{
bt=new Node;
bt->data=s;
count++;
bt->Lchild=Create(bt->Lchild);
bt->Rchild=Create(bt->Rchild);
}
return bt;
}
void BiTree::qian(Node *bt)
{
if(bt==NULL) return;
else
{
cout<<bt->data<<" ";
qian(bt->Lchild);
qian(bt->Rchild);
}
}
void BiTree::zhong(Node *bt)
{
if(bt==NULL) return;
else
{
zhong(bt->Lchild);
cout<<bt->data<<" ";
zhong(bt->Rchild);
}
}
void BiTree::hou(Node *bt)
{
if(bt==NULL) return;
else
{
hou(bt->Lchild);
hou(bt->Rchild);
cout<<bt->data<<" ";
}
}
void BiTree::ceng(Node *bt) //层序遍历
{
Node *temp[100]; //创建pTreeNode指针类型的指针数组
int in = 0;
int out = 0;
temp[in++] = bt; //先保存二叉树根节点
while (in > out)
{
if (temp[out])
{
cout << temp[out]->data<<" ";
temp[in++] = temp[out]->Lchild;
temp[in++] = temp[out]->Rchild;
}
out++;
}
}
void BiTree::Release(Node *bt)
{
if(bt!=NULL){
Release(bt->Lchild);
Release(bt->Rchild);
delete bt;
}
}
int main()
{
BiTree one;
one.qian();
cout<<endl;
one.zhong();
cout<<endl;
one.hou();
cout<<endl;
one.ceng();
return 0;
}