uva 122
题目大意:给出一组二叉树的节点,输出层序遍历的结果,如果路径不完整,输出“not complete"
#include <vector>
#include <iostream>
#include <queue>
#include <fstream>
using namespace std;
#define TEST 0
typedef struct Node *pNode;
struct Node
{
int able;
int v;
pNode l, r;
Node() : able(0), l(NULL), r(NULL) {}
};
pNode root;
vector<int> ans;
ofstream ofs;
void removeTree(pNode d)
{
if (d == NULL)
return;
if (d->l)
removeTree(d->l);
if (d->r)
removeTree(d->r);
delete d;
}
bool readInput()
{
while (getchar() != '(')
continue;
if (cin.peek() == ')')
return false;
int v;
char c;
pNode p = root;
cin >> v;
getchar();
while (1)
{
c = getchar();
if (c == 'L')
{
if (!p->l)
p->l = new Node;
p = p->l;
}
if (c == 'R')
{
if (!p->r)
p->r = new Node;
p = p->r;
}
if (c == ')')
break;
}
p->able++;
p->v = v;
return true;
}
bool bfs()
{
pNode cur;
queue<pNode> q;
q.push(root);
while (q.size())
{
cur = q.front();
q.pop();
if (cur->able != 1)
return false;
ans.push_back(cur->v);
if (cur->l)
q.push(cur->l);
if (cur->r)
q.push(cur->r);
}
return true;
}
void showAns()
{
for (int i = 0; i != ans.size(); ++i)
(TEST ? ofs : cout) << ans.at(i) << (i == ans.size() - 1 ? "" : " ");
(TEST ? ofs : cout) << '\n';
}
int main()
{
if (TEST)
{
ofs.open("/home/lixiaoqi/Documents/Code/C++/1.txt");
if (!ofs.is_open())
throw runtime_error("FILE NOT OPEN!");
}
while (cin.peek() != EOF)
{
root = new Node;
while (readInput())
continue;
if (bfs())
showAns();
else
(TEST ? ofs : cout) << "not complete\n";
ans.clear();
removeTree(root);
cin.ignore(1024, '\n');
}
return 0;
}
|