#include<iostream>
using namespace std;
typedef struct Tree {
char date;
Tree* left;
Tree* right;
}*Btree;
void creat_tree(Btree &T) {// 树的创建
char ch;
cin >> ch;
if (ch == '#') {
T = NULL;
}
else {
T = new Tree;
T->date = ch;
creat_tree(T->left);
creat_tree(T->right);
}
}
void get_tree1(Btree T) {//树的前序遍历输出
if (T != NULL)
{
cout << T->date << " ";
get_tree1(T->left);
get_tree1(T->right);
}
}
void get_tree2(Btree T) {//树的中序遍历输出
if (T != NULL)
{
get_tree2(T->left);
cout << T->date << " ";
get_tree2(T->right);
}
}
void get_tree3(Btree T) {//树的后序遍历输出
if (T != NULL)
{
get_tree3(T->left);
get_tree3(T->right);
cout << T->date << " ";
}
}
void put(Btree &T) {
cout << T->date << " ";
}
void get_tree4(Btree &T) {//树的层次遍历输出
Btree a[100],p;
p = new Tree;
int front, rear;
if (T != NULL) {
a[0] = T;
front = -1;
rear = 0;
while (front < rear) {
p = a[++front];
put(p);
if (p->left != NULL) {
a[++rear] = p->left;
}
if (p->right != NULL) {
a[++rear] = p->right;
}
}
}
}
int main()
{
Btree T=new Tree;
creat_tree(T);
get_tree1(T);
cout << endl;
get_tree2(T);
cout << endl;
get_tree3(T);
cout << endl;
get_tree4(T);
return 0;
}
遍历
最新推荐文章于 2024-07-15 20:51:08 发布