大白2,P150页
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
const int N = 100009;
struct Node
{
bool have_value;
int v;
Node *left,*right;
Node(): have_value(false),left(NULL),right(NULL) {}
};
using namespace std;
bool failed = false;
Node* root;
vector<int> ans;
void addnode(int v,char*s);
Node* newnode(){return new Node;}
bool bfs(vector<int>& res);
int main()
{
while(1)
{
failed = false;
char s[N];
root = newnode();
while(1)
{
if(scanf("%s",s) !=1) return 0;
if(!strcmp(s,"()")) break;
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,‘,‘)+1);
}
bfs(ans);
if(!root->have_value) failed = true;
if(!failed)
{
for(int i = 0 ; i <= ans.size()-1 ; i++)
{
if(i!=0) printf(" ");
printf("%d",ans[i]);
}
puts("");
}
else
puts("not complete");
}
}
void addnode(int v, char * s)
{
Node *u = root;
int n = strlen(s);
for(int i = 0 ; i < n ; i++)
{
if(s[i] == ‘L‘)
{
if(u->left == NULL) u->left = newnode();
u = u->left;
}
else if(s[i] == ‘R‘)
{
if(u->right == NULL) u->right = newnode();
u = u ->right;
}
}
if(u->have_value) failed = true;
u->v = v;
u->have_value = true;
}
bool bfs(vector<int>& ans)
{
ans.clear();
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();q.pop();
if(!temp->have_value) return false;
if(temp->left != NULL) q.push(temp->left);
if(temp->right != NULL) q.push(temp->right);
ans.push_back(temp->v);
}
return true;
}
版权声明:本文为博主原创文章,允许非商业性转载,转载必须著名作者(CSDN tt2767)与本博客链接:http://blog.csdn.net/tt2767。
原文地址:http://blog.csdn.net/tt2767/article/details/46970805