根据紫书,与vjudge上的大佬的代码写出来的代码,惭愧!!
PS:
udebug尽管比较好,但是其中的样例不一定是对的,本题udebug中得到的结果并不对,不可ac。
经典建树的题,可以分为几个方面:
- 节点的各个信息 struct node
- 创立新节点 node * newnode()创建新节点,并返回其指针
- 添加新节点, 节点不存在时,创建新节点,存在时,跳过
- 用BFS遍历,queue来存每一层的节点的指针,并以此来输出需要输出的值,按层遍历。
#include <iostream>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
vector<int>v;
bool failed=false;
struct node
{
bool have_value;
int value;
node *left,*right;
node():have_value(false),left(NULL),right(NULL){}//构造函数
};
node *root;//创立根节点
node *newnode()//创建新节点并返回地址。
{
return new node;
}
void addnewnode(int x,char *c)
{
int n=strlen(c);
node *r=root;
for(int i=0;i<n;i++)
{
if(c[i]=='L')
{
if(r->left==NULL) r->left=newnode();
r=r->left;
}
else if(c[i]=='R')
{
if(r->right==NULL) r->right=newnode();
r=r->right;
}
}
if(r->have_value) failed=true;
r->value=x;
r->have_value=true;
}
bool bfs(vector<int>&v)
{
v.clear();
queue<node*>q;
q.push(root);
while(!q.empty())
{
node* r=q.front();
q.pop();
if(!r->have_value)
return false;
if(r->left!=NULL) q.push(r->left);
if(r->right!=NULL) q.push(r->right);
v.push_back(r->value);
}
return true;
}
int main()
{
// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(1)
{
char s[200000];
failed=false;
root=newnode();
while(1)
{
int num;
if(scanf("%s",s)!=1) return 0;
if(!strcmp(s,"()")) break;
sscanf(&s[1],"%d",&num);
addnewnode(num,strchr(s,',')+1);
}
bfs(v);
if(!root->have_value) failed=true;
if(failed)
cout<<"not complete"<<endl;
else
{
for(int i=0;i<v.size();i++)
{
if(i!=0)
cout<<" ";
cout<<v[i];
}
cout<<endl;
}
}
return 0;
}