用结构体实现了不完全二叉树
- 用到了不熟悉的构造函数
- 多个模块分开写成函数
- 用了几个str的操作
- 队列实现BFS,vectro储存结果
- 注意输出not complete 的情况,要考虑周全,然后用一个failed来判断。
- 用数组来表示这种数据结构也行。
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<cstdlib>
using namespace std;
const int MAX=20;
bool failed;
char s[MAX];
vector<int> ans;
struct Node
{
bool have_value;
int v;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){};//构造函数
};
Node *newnode()
{
return new Node(); //申请内存,再用构造函数,封装再newnode这个函数里面.
}
Node* root=newnode();
void addnode(int v,char *s)
{
int n=strlen(s);
Node *u=root;
for(int i=0;i<n;i++)
{
if(s[i]=='L')
{
if(u->left==NULL)
u->left=newnode();
u=u->left;
}
if(s[i]=='R')
{
if(u->right==NULL)
u->right=newnode();
u=u->right;
}
// printf("the value of have_value is%d\n",u->have_value);
}
// printf("%d",failed);
if(u->have_value==true) failed = true;
// printf("%d",failed);
u->v=v;
u->have_value=true;
}
bool read_input()
{
failed = false;
while(1)
{
// printf("1\n");
if (scanf("%s",s)==EOF)
return false;
else
{
if(!strcmp(s,"()"))
break;
int v;
sscanf(s+1,"%d",&v);
addnode(v,strchr(s,',')+1); //这里不用特意再储存一个pos字符串,可以直接用s里面的地址,反正最后都是'\0'结尾,在addnode里面使用strlen(s)就可以了
}
}
return true;
}
bool bfs(vector<int> &ans) //队列实现BFS
{
queue<Node*> q;
ans.clear();
q.push(root);
while(!q.empty())
{
Node *u=q.front();
q.pop();
if(!u->have_value)
{
failed=true;
return false;
}
ans.push_back(u->v);
if(u->left) q.push(u->left);
if(u->right)q.push(u->right);
}
return true;
}
int main(void)
{
while (1)
{
if(read_input()==0)
return 0;
// printf("1\n");
bfs(ans);
if(failed)
{
printf("not complete");
return 0;
}
for (int i=0;i<ans.size();i++)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}