#include<iostream>
using namespace std;
#include<malloc.h>
#define MaxSize 50
typedef char ElemType;
//类型定义
typedef struct node
{
ElemType data;
struct node *Ichild; //左孩子
struct node *rchild; //右孩子
}BTNode;
//创建二叉树
void CreatBTNode(BTNode *&b, ElemType str[])
{
BTNode *st[MaxSize], *p;
int top = -1, k, j = 0;
ElemType ch;
b = NULL; //二叉树初始时为空
ch = str[j];
while (ch != '\0') //循环扫描每一个字符
{
switch (ch)
{
case '(': top++; st[top] = p; k = 1; break; //开始处理左孩子节点
case ')': top--; break;
case ',': k = 2; break; //开始处理右孩子节点
default: p = (BTNode *)malloc(sizeof(BTNode));
p->data = ch;
p->Ichild = NULL;
p->rchild = NULL;
if (b == NULL) //没有建立根节点
b = p; //*p作为二叉树根节点
else
{
switch (k)
{
case 1: st[top]->Ichild = p; break;
case 2: st[top]->rchild = p; break;
}
}
}
j++;
ch = str[j];
}
}
//输出二叉树
void DispBTNode(BTNode *b)
{
if (b != NULL)
{
cout << b->data;
if (b->Ichild != NULL || b->rchild != NULL)
{
cout << "(";
DispBTNode(b->Ichild);
if (b->rchild != NULL)
cout << ",";
DispBTNode(b->rchild);
cout << ")";
}
}
}
//采用先序遍历求叶子节点到根节点的逆路径
void PreOrder(BTNode *b)
{
BTNode *st[MaxSize], *p;
int top = -1;
if (b != NULL)
{
top++;
st[top] = b;
while (top > -1)
{
p = st[top];
top--;
if (p->rchild == NULL&&p->Ichild == NULL)
{
cout << b->data;
for(int i=1;i<=top;i++)
cout << st[i]->data;
cout << " ";
}
if (p->rchild != NULL)
{
top++;
st[top] = p->rchild;
}
if (p->Ichild != NULL)
{
top++;
st[top] = p->Ichild;
}
}
cout << endl;
}
}
//采用后序非递归遍历求叶子节点到根节点的逆路径
void PostOrder(BTNode *b)
{
BTNode *p;
BTNode *st[MaxSize];
int flag, i, top = -1; //栈顶指针赋初值
if (b != NULL)
{
do
{
while (b != NULL)
{
top++;
st[top] = b;
b = b->Ichild;
}
p = NULL; //p指向栈顶节点的前一个已经访问过的节点
flag = 1; //标记已经访问过的
while (top != -1 && flag)
{
b = st[top];
if (b->rchild == p)
{
if (b->rchild == NULL&&b->Ichild == NULL)
{
cout << st[0]->data;
for (i = 1; i <= top; i++)
cout << st[i]->data;
cout << " ";
}
top--;
p = b;
}
else
{
b = b->rchild;
flag = 0;
}
}
} while (top != -1);
cout << endl;
}
}
//采用层次遍历求叶子节点到根节点的逆路径
void LevelOrder(BTNode * b)
{
struct snode
{
BTNode *node;
int parent;
}qu[MaxSize];
BTNode *q;
int front, rear, p;
front = rear = -1; //置队列为空队列
rear++;
qu[rear].node = b; //根节点指针进队
qu[rear].parent = -1; //根节点没有双亲节点
while (front != rear) //队列不为空
{
front++;
q = qu[front].node;
if (q->Ichild == NULL&&q->rchild == NULL)
{
cout << b->data;
p = front;
while (qu[p].parent != -1)
{
cout << qu[p].node->data;
p = qu[p].parent;
}
cout << " ";
}
if (q->Ichild != NULL)//左孩子进队
{
rear++;
qu[rear].node = q->Ichild;
qu[rear].parent = front;
}
if (q->rchild != NULL)//右孩子进队
{
rear++;
qu[rear].node = q->rchild;
qu[rear].parent = front;
}
}
}
//主函数调用
int main()
{
BTNode *b;
CreatBTNode(b, "A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
cout << "输出二叉树:";
DispBTNode(b);
cout << endl;
cout << "采用先序遍历求叶子节点到根节点的逆路径:" << endl;
PreOrder(b);
cout << endl;
cout << "采用后序非递归遍历求叶子节点到根节点的逆路径:" << endl;
PostOrder(b);
cout << endl;
cout << "采用层次遍历求叶子节点到根节点的逆路径:" << endl;
LevelOrder(b);
system("pause");
}