#include
using namespace std;
typedef struct LNode {
char data;
struct LNode* lchild, * rchild;
}LNode,*Tree;
typedef struct LNode_Stack{
LNode* data;
struct LNode_Stack* next;
}*Stack;//*不能忘记
void initStack(Stack& S) {
S = NULL;
}
void push(Stack& S, LNode *p) {
LNode_Stack* r = new LNode_Stack;
r->data = p;
r->next = S;
S = r;
}
bool pop(Stack& S, Tree& p) {
if (S == NULL)
return false;
else {
p = S->data;
S = S->next;
}
return true;
}
//这里的出栈问题要注意,不能用LNode
bool emptyStack(Stack S) {
if (S == NULL)
return true;
return false;
}
void getStack(Stack S,Tree &p) {
p = S->data;
}
void initTree(Tree& T) {
T = NULL;
}
void buildTree_pre(Tree& T) {
char e;
cin >> e;
if (e == '@')
T = NULL;//递归出口
else {
T = new LNode;
T->data = e;
buildTree_pre(T->lchild);
buildTree_pre(T->rchild);
}
}
void visit(Tree T) {
cout << T->data << " ";
}
void order_pre(Tree T) {
if (T != NULL) {
visit(T);
order_pre(T->lchild);
order_pre(T->rchild);
}
}
void order_mid(Tree T) {
if (T != NULL) {
order_mid(T->lchild);
visit(T);
order_mid(T->rchild);
}
}
void order_post(Tree T) {
if (T != NULL) {
order_post(T->lchild);
order_post(T->rchild);
visit(T);
}
}
void ruTree_mid(Tree T,Stack &S) {
while (T!= NULL) {
push(S, T);
T = T->lchild;
}
}
//void order_no_mid(Tree T) {
// Stack S;
// initStack(S);
// LNode* p = NULL;
// ruTree_mid(T, S);
// while (!emptyStack(S)) {
// pop(S, p);
// visit(p);
// if (p->rchild)
// ruTree_mid(p->rchild, S);
// }
//}
void ruTree_pre(Tree T, Stack& S) {
while (T != NULL) {
visit(T);
push(S, T);
T = T->lchild;
}
}
void order_no_pre(Tree T) {
Stack S;
initStack(S);
LNode* p = NULL;
ruTree_pre(T, S);
while (!emptyStack(S)) {
pop(S, p);
//visit(p);
if (p->rchild)
ruTree_pre(p->rchild, S);
}
}
//一直走到左下,若右子树不空,则将右子树重复
//出栈,访问
//先序遍历即先访问再入栈
void order_no_mid(Tree T) {
Stack S;
initStack(S);
LNode* p = T;
while (p||!emptyStack(S)) {
if (p != NULL) {
//visit(p);
push(S, p);
p = p->lchild;
}
else {
pop(S, p);
visit(p);
p=p->rchild;
}
}
}
//一直走到左下,若右下不空且未访问,右子树重复
//出栈,访问,标记最近访问结点,置空
void order_no_post(Tree T) {
Stack S;
initStack(S);
LNode* p = T;
LNode* r = NULL;//visit的结点标记
while (p || !emptyStack(S)) {
if (p) {
push(S, p);
p = p->lchild;
}
else {
getStack(S, p);
if (p->rchild && p->rchild != r)
p = p->rchild;
else {
pop(S, p);
visit(p);
r = p;
p = NULL;//这里为什么要重置
}
}
}
}
int main() {
Tree T;
initTree(T);
buildTree_pre(T);
//ab@@cd@@@@
cout << "中序遍历" << endl;
order_mid(T);
cout << endl;
cout << "后序遍历" << endl;
order_post(T);
cout << endl;
cout << "先序遍历" << endl;
order_pre(T);
cout << endl;
cout << "非递归中序遍历" << endl;
order_no_mid(T);
cout << endl;
cout << "非递归先序遍历" << endl;
order_no_pre(T);
order_no_post(T);
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)