Trees on the level UVA - 122

不得不说作为二叉树的入门第一题还是很有代表性的;

代码是根据刘汝佳的代码打的,然后自己写了注释就当熟悉一下流程

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <vector>
#include <queue>
#define maxn 1000
using namespace std;
bool failed;
char s[maxn];
struct Node {//用指针定义左子树和右子树
    bool have_value;
    int v;
    Node *left,*right;
    Node():have_value(false),left(NULL),right(NULL){};

};
Node *root;
Node *newnode()
{
    return new Node();//new的同时调用了构造函数
}
void addnode(int v,char*s)
{
    int n=strlen(s);
    Node *u=root;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='L')//如果是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)  //如果已经赋值返回ture这个主要是给not compile 那个样例做的
        failed=true;
    u->v=v;  //赋值
    u->have_value=true;

}

bool read_input()
{
    failed=false;
    root=newnode();
    for(;;)
    {
        if(scanf("%s",s)!=1)
            return false;
        if(!strcmp(s,"()"))
            break;
        int v;
        sscanf(&s[1],"%d",&v);
        addnode(v,strchr(s,',')+1);
    }
    return 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->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(read_input())
    {
    vector<int>v;
    if(!bfs(v))
        failed=true;

    if(failed)
        cout<<"not complete"<<endl;
    else {
        vector<int>::iterator it=v.begin();
    for(;it!=v.end();it++)
    {
        if(it!=v.begin())
            cout<<" ";
        cout<<*it;


    }
    cout<<endl;
    }}
        return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务