首先,
这篇文章讲解关于二叉树的三种遍历
十分不错的https://www.cnblogs.com/SHERO-Vae/p/5800363.html
特别鸣谢 @烟雨迷离半世觞 提供
一共写了四个文件
main.cpp自然是main函数的文件
hand.h这个头文件不仅仅是卷入了一些必要的头文件,主要是写了两个基本的结构体定义,box是用来表示散列的结构体,bitnode则是二叉树的结点
头文件stack.h定义了顺序栈。头文件tree.h定义了二叉树。
以下是源代码:
hand.h
#pragma once
#include<iostream>
#include<stdlib.h>
#include<ctype.h>
using namespace std;
typedef struct bitnode
{
public:
char data;
bitnode *lchild, *rchild;
}bitnode, *bitree;
typedef struct box
{
bitnode *data;
int flag;//flag用于标记,用于记录该节点出栈的次数
}box,*boxtree;
main.cpp
#include"tree.h"
int main(void)
{
bitt A;
cout << "顺序输入一棵树:" << endl;
A.createbitt();
cout << "以不采用递归的后序遍历输出:" << endl;
A.inorderbitt();
system("pause");
return 0;
}
stack.h
#pragma once
#include"head.h"
#define stacksize 100
class stack
{
private:
boxtree *top;
box **base;
int size;
public:
stack();
~stack(){}
void push(box* e);
void pop(box *&e);
box* getTop();
bool isEmpty() { if (top == base) return true; else return false; }
};
stack::stack()
{
base = top = new boxtree[stacksize];
size = stacksize;
}
box* stack::getTop()
{
top--;
box* temp=*top;
top++;
return temp;
}
void stack::push(box* e)
{
*top++ = e;
}
void stack::pop(box *&e)
{
if (top == base)
{
cout << "空栈,无法出栈" << endl;
system("pause");
}
else
e = *--top;
}
tree.h
#pragma once
#include"stack.h"
class bitt
{
bitnode *pt;
void create(bitnode *&t);
void inorder(bitnode *t);
public:
void createbitt() { bitnode *t; create(t); pt = t; }
void inorderbitt() { bitnode *t = pt; inorder(t); }
};
void bitt::create(bitnode *&t)
{
char ch;
cin >> ch;
if (ch == '.') t = NULL;
else
{
t = new bitnode;
t->data = ch;
create(t->lchild);
create(t->rchild);
}
}
void bitt::inorder(bitnode *t)
{
stack s;
bitnode *p = t;
box *temp;
while (p || !s.isEmpty())
{
while (p)
{
box* b = new box;
b->data = p;
b->flag = 0;
s.push(b);
p = p->lchild;
}
if (!s.isEmpty())
{
temp = s.getTop();
s.pop(temp);
if (temp->flag == 0)//这边原来写成了temp->flag=0,TM这个找了半天才发现
{
temp->flag = 1;
p = temp->data->rchild;
s.push(temp);
}
else
{
cout << temp->data->data;
p = NULL;
}
}
}
cout << endl;
}
END