【问题描述】
给出一个按照“扩展遍历序列”的扩展先序遍历序列字符串,'.' 代表空的子节点,大写字母代表节点内容。请通过这个字符串建立二叉树,并参考课件上的算法,对该树利用栈进行非递归算法的遍历。注意,不用栈和非递归算法 不给分!
【输入形式】
输入只有1行 (以回车结束),包含一个字符串S,用来建立二叉树。保证S为合法的二叉树扩展先序遍历字符串,节点内容只有大写字母,且S的长度不超过80。
【输出形式】
输出对该树先序遍历得出的节点序列。
【样例输入】
AB.DF..G..C.E.H..(回车)
【样例输出】
ABDFGCEH
#include <iostream>
#include <stack>
using namespace std;
typedef struct node
{
char data;
node *l, *r;
} * Bintree;
char cp[101];
node *creat(int *n)
{
if (cp[*n] != '.')
{
node *root = new node;
root->data = cp[*n];
(*n)++;
root->l = creat(n);
(*n)++;
root->r = creat(n);
return root;
}
else
return NULL;
}
void pri(Bintree t)
{
stack<Bintree> s;
while (t || !s.empty())
{
if (t != NULL)
{
cout << t->data;
s.push(t);
t = t->l;
}
else
{
t = s.top();
s.pop();
t = t->r;
}
}
}
int main()
{
cin >> cp;
int a = 0;
Bintree root = creat(&a);
pri(root);
}