#include <iostream>
#include <string>
using namespace std;
// 定义树结构;
struct Tree {
string data;
Tree *lchild, *rchild;
};
// 定义栈结构;
struct Stack {
Tree* data;
Stack *next;
};
// 定义类;
class CTreestack {
public:
// 初始化栈;
Stack *Init() {
Stack *top;
top = new Stack;
top->next = NULL;
return top;
}
//树的结点的指针地址进栈;
void Push(Tree* t, Stack *top){
Stack *p;
p = new Stack();
p->data = t;
p->next = top->next;
top->next = p;
}
//树的结点的指针地址出栈;
Tree *Pop(Stack *top) {
Stack *p;
Tree *s;
p = top->next;
s = p->data;
top->next = p->next;
delete p;
return s;
}
};
// 创建树的结点;以及输入结点的数据;
Tree *Create() {
Tree *t, *p, *s[50];
int i, j;
while (1) {
cout << "请输入结点序列号:\n";
cin >> i;
if (i == 0)
break;
else {
p = new Tree();
cout << "请输入结点数据:\n";
cin >> p->data;
s[i] = p;
if (i == 1)
t = p;
else {
j = i/2;
if (i%2 == 0)
s[j]->lchild = p;
else
s[j]->rchild = p;
}
}
}
return t;
}
void Visite(Tree *p) {
cout << p->data << "\t";
}
void Preorder(Tree *t) {
Stack *top;
// 定义类名为 a ;
CTreestack a;
Tree *p = t;
// 在Treestack类里面初始化栈函数Iint;栈的头指针为top;
top = a.Init();
// p!= NULL 为树的结点不为空 或者 top->next != NULL栈不为空(因为栈的头指针的数据域是没有数据的,所以为top->next != NULL不能为top != NULL);若都为空;说明到了最后一个结点了;他们左右指针都是为NULL;
while (p != NULL || top->next != NULL) {
if (p != NULL) {
// 访问结点的数据;
Visite(p);
// 树的结点指针进栈;然后指向其左结点;直到为空;在从栈顶取出元素给p, 也就是 p = a.Pop(top);;在使p指向栈顶元素的右结点p = p->rchild;;在判断p是否为空,若不为空;在访问其数据后使p在指向其左结点;直到为空在从栈顶取出元素;p 在指向其元素的右结点;
a.Push(p, top);
p = p->lchild;
}
else {
p = a.Pop(top);
p = p->rchild;
}
}
}
int main() {
// 定义树的根指针t;
Tree *t;
//创建树的结点函数Create;
t = Create();
// 输入树的结点函数Preorder;
Preorder(t);
return 0;
}