输入的先序数据为ABC##DE#G##F###
输入数据的 二叉链表图为:
按照中序的规则, 中序输出预期为:CBEGDFA
代码如下:
// 二叉树.cpp: 实现二叉树的创建和中序遍历输出节点数据。
//
#include "stdafx.h"
#include "type.h"
#include "stack.h"
using namespace std;
template <class TElemType>
class Binode {
public:
TElemType data;
Binode *lchild, *rchild;
};
template <class TElemType>
class Bitree
{
public :
Bitree();
~Bitree();
Binode<TElemType> * creatBitree() {
cout << "请输入 节点值" << endl;
TElemType ch;
Binode<TElemType> * t;
cin >> ch;
if (ch == '#') t = NULL;
else {
//if (!(Tree = new Bitree)) exit(overflow_error);
t = new Binode<TElemType>;
t->data = ch;
t->lchild = creatBitree();
t->rchild = creatBitree();
}
return t;
}
void creat()
{
root = creatBitree();
}
Status InoderTraverse( Status(*visit)(TElemType e))//*visit为函数指针
{
//中序非递归遍历Tree二叉树
Binode<TElemType> * p = root;
stack<Binode<TElemType> *> s;
s.InitStack();
while (p != NULL || !s.IsEmpty())//如果 p不是空二叉树,或者 存到 的s栈中还有东西能输出
{
while (p != NULL)//一直沿着左孩子压栈压到底或者是当右孩子不为空时压入右孩子
{
s.Push(p); p = p->lchild;
}
if (!s.IsEmpty())//到了这一步,退出了上一个while循环体,说明 左孩子到底了,进行输出了
{
s.Pop(p); if (!visit(p->data))return ERROR;
p = p->rchild;
}
}
return OK;
}
private:
Binode<TElemType> * root;
};
template <class TElemType>
Bitree<TElemType>::Bitree()
{
}
template <class TElemType>
Bitree<TElemType>::~Bitree()
{
}
template <class TElemType>
Status Printelem(TElemType e)
{
cout << e;
return OK;
}
int main()
{
Bitree<char> Mytree;
Mytree.creat();
Mytree.InoderTraverse(&Printelem);
system("pause");
return 0;
}
其中,栈的结构声明在stack.h中,代码如下:
#pragma once
#include"type.h"//定义的ERROR、OK等
#include <string>
#define STACK_INIT_SIZE 100
#define STCAK_INCREASMENT 10
using namespace std;
template <class type>
class stack {
private:
type * base;//栈底
type * top;//栈顶
int stacksize;//当前已分配的存储空间,以元素为单位
public:
stack() :base(NULL), top(NULL) {}
Status InitStack() {
//分配一个空栈
base = new type[STACK_INIT_SIZE];
if (base == NULL)return ERROR;
top = base;
stacksize = STACK_INIT_SIZE;
return OK;
}
Status GetTop(type &e) {
//若栈不为空栈,那么返回栈顶元素
if (base == top)return ERROR;
e = *(top - 1);//因为top指的是最后一个元素的下一个元素
return OK;
}
Status Push(type e) {
if (top == NULL) {//栈满
type * newbase = NULL;
newbase = new type[(STCAK_INCREASMENT + STACK_INIT_SIZE)];
if (newbase == NULL) return ERROR;
memcpy(newbase, base, stacksize * sizeof(type));
delete[] base;
base = newbase;
stacksize += STCAK_INCREASMENT;
}
*(top++) = e;
return OK;
}
Status Pop(type &e) {
if (base == top) return ERROR;
e = *(--top);
return OK;
}
Status PrintStack() {
if (base == top) return ERROR;
type * p = base;
while (p != top) {
cout << *p << ",";
p++;
}
cout << endl;
}
Status ClearStack() {
if (base == top) return OK;
type tmp;
while (base != top) {
Pop(tmp);
}
if (base == top) return OK;
else return ERROR;
}
Status IsEmpty() {
if (base == top) return TRUE;
else return FALSE;
}
};
最终中序输出的结果为: