6-7 树的层次遍历 uva122

时间:2021-12-24 20:42:59

非常不熟练  照着书大的

晚上尝试一下自己打  了解二叉树  用数组打

第一次:

#include<bits/stdc++.h>
using namespace std;
bool failed; void addnode(int v,char *s);
char s[];
struct node
{
bool flag;
int v;
node *left,*right;
node():flag(false),left(NULL),right(NULL){} };
node *root;
node *newnode(){return new node();}
bool read_input()
{
failed=false;
root=newnode();
for(;;)
{
if(scanf("%s",s)!=)return false;
if(!strcmp(s,"()")) break;
int v;
sscanf(&s[],"%d",&v);
addnode(v,strchr(s,',')+); }
return true; } void addnode(int v,char *s)
{
int n=strlen(s);
node *u=root;
for(int i=;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->flag)failed=true;
u->v=v;
u->flag=true; } bool bfs (vector<int>&ans)
{
queue<node*>q; ans.clear();
q.push(root);
while(!q.empty())
{
node *u=q.front();q.pop();
if(!u->flag)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()
{ vector<int>ans;
while(read_input())
{
if(!bfs(ans))failed=true;
if(failed)printf("not complete\n");
else
{
for(int i=;i<ans.size();i++)
{
if(i==ans.size()-)printf("%d\n",ans[i]);
else printf("%d ",ans[i]); } } } return ;
}