uva122_二叉树的层次历遍

来源:互联网 发布:李炎恢php第四季下载 编辑:程序博客网 时间:2024/04/28 22:04

大白2,P150页

#include<cstdio>#include<iostream>#include<cstring>#include<vector>#include<queue>const int N = 100009;struct Node{    bool have_value;    int v;    Node *left,*right;    Node(): have_value(false),left(NULL),right(NULL) {}};using namespace std;bool failed = false;Node* root;vector<int> ans;void addnode(int v,char*s);Node* newnode(){return new Node;}bool bfs(vector<int>& res);int main(){    while(1)    {        failed = false;        char s[N];        root = newnode();        while(1)        {            if(scanf("%s",s) !=1) return 0;            if(!strcmp(s,"()"))      break;            int v;            sscanf(&s[1],"%d",&v);            addnode(v,strchr(s,',')+1);        }        bfs(ans);        if(!root->have_value) failed = true;        if(!failed)        {            for(int i = 0 ; i <= ans.size()-1 ; i++)            {                if(i!=0)            printf(" ");                printf("%d",ans[i]);            }            puts("");        }        else            puts("not complete");    }}void addnode(int v, char * s){    Node *u = root;    int  n = strlen(s);    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 bfs(vector<int>& ans){    ans.clear();    queue<Node*> q;    q.push(root);    while(!q.empty())    {        Node* temp = q.front();q.pop();        if(!temp->have_value) return false;        if(temp->left != NULL)     q.push(temp->left);        if(temp->right != NULL)     q.push(temp->right);        ans.push_back(temp->v);    }    return true;}
0 0
原创粉丝点击