#include <iostream>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include<cstring>
#include <typeinfo>
#include <vector>
#include <queue>
using namespace std;
#define N 100000
char s[N];
struct Node
{
bool have_value;//是否被赋值
int v;//赋值;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
};
Node *root;//根节点。
bool failed;//是否有输入错误。
Node * newNode()
{
return new Node(); //申请内存并运用构造函数;
}
void adenode(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;
}
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 reint()
{
failed=false;//没有输入错误
for(;;)
{
int v;
if(scanf("%s",s)!=1)
return false;
if(!strcmp(s,"()"))
break;
sscanf(&s[1],"%d",&v);//提取值
adenode(v,strchr(s,',')+1);//strstr返回,的位置
}
return true;
}
bool bfs(vector<int>&ans)
{
queue<Node*>q;
q.push(root);
while(!q.empty())
{
Node *u=q.front();
q.pop();
if(!u->have_value)return false;
ans.push_back(u->v);
if(u->left!=NULL)
q.push(u->left);
if(u->right!=NULL)
q.push(u->right);
}
return true;
}
int main()
{
while(1)
{ root = newNode();
if(!reint())
break;
vector<int>ans;
if(!failed&&bfs(ans))
{
for(int i=0; i<ans.size(); i++)
printf("%d%c",ans[i],i==ans.size()-1? '\n':' ');
}
else
printf("not complete\n");
}
return 0;
}
#include <cstring>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include<cstring>
#include <typeinfo>
#include <vector>
#include <queue>
using namespace std;
#define N 100000
char s[N];
struct Node
{
bool have_value;//是否被赋值
int v;//赋值;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
};
Node *root;//根节点。
bool failed;//是否有输入错误。
Node * newNode()
{
return new Node(); //申请内存并运用构造函数;
}
void adenode(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;
}
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 reint()
{
failed=false;//没有输入错误
for(;;)
{
int v;
if(scanf("%s",s)!=1)
return false;
if(!strcmp(s,"()"))
break;
sscanf(&s[1],"%d",&v);//提取值
adenode(v,strchr(s,',')+1);//strstr返回,的位置
}
return true;
}
bool bfs(vector<int>&ans)
{
queue<Node*>q;
q.push(root);
while(!q.empty())
{
Node *u=q.front();
q.pop();
if(!u->have_value)return false;
ans.push_back(u->v);
if(u->left!=NULL)
q.push(u->left);
if(u->right!=NULL)
q.push(u->right);
}
return true;
}
int main()
{
while(1)
{ root = newNode();
if(!reint())
break;
vector<int>ans;
if(!failed&&bfs(ans))
{
for(int i=0; i<ans.size(); i++)
printf("%d%c",ans[i],i==ans.size()-1? '\n':' ');
}
else
printf("not complete\n");
}
return 0;
}
本文介绍了一种使用二叉树结构存储和检索数据的方法。通过定义节点结构和插入操作,实现了一个简单的二叉树,并利用广度优先搜索完成了树的遍历,最后输出了树中所有已赋值节点的数据。
509

被折叠的 条评论
为什么被折叠?



