这个题目的来源是紫书上的,值得学习他的构建思路
首先先上题目和解析
然后默默的贴上代码实际上就是把书上的敲了一遍
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
struct node{
bool have_value;
int v;
node *left,*right;
node():have_value(false),v(0),left(NULL),right(NULL){}
//构建结构体的方法我自己也不是很清楚
};
bool failed;
node* root;//头节点
char sz[100000];
node* newnode() {return new node();}
void addnode(int v,char* s){
int n=strlen(sz);
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;
}
}
if(u->have_value)
failed=true;
u->v=v;
u->have_value=true;
}
bool read_input(){
root = newnode();
for(;;){
if(scanf("%s",sz)!=1) return false;
if(!strcmp(sz,"()")) break;//两个结束标志
int v;
sscanf(&sz[1],"%d",&v);//固定输入方式,就是把sz[i]的地址存的数给v
//还可以这样使用 sscanf("asd","%d",&v);
addnode(v,strchr(sz,',')+1);//这个函数的意思数找到第一个,返回他的地址
}
return true;
}
vector<int> ans;
bool bfs(){
queue<node*> q;
ans.clear();
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;
}
void print()
{
for(int i=0;i<ans.size();i++)
printf("%d%c",ans[i],i==ans.size()-1?'\n':' ');//选择输出,不知道怎么写
}
int main()
{
while(read_input()){
if(failed){
cout<<"not complete"<<endl;
continue;
}
if(bfs())
print();
else
cout<<"not complete"<<endl;
}
return 0;
}
嘻嘻,希望你学会了这样的格式,我觉得真的很完善
ps:没有写释放空间的函数,可以参考图片
爱你,么么