122 - Trees on the level[构建二叉树]

来源:互联网 发布:键盘打字指法软件 编辑:程序博客网 时间:2024/05/19 12:11

uva的老题了,练一练代码能力和二叉树的建立吧算是

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<map>#include<vector>#include<stack>#include<queue>#include<set>#include<list>#include<cmath>using namespace std;typedef long long LL;#define LEN  300#define MAXD 100struct Node{    int value;    int have_value;    Node *Left;    Node *Right;};Node* root;Node* array[LEN];int ok ;char str[MAXD];void BuildTree(){    int value;    sscanf(str + 1, "%d" , &value);    int pos = strchr(str,',') - str;    Node *node = root;    for(int i = pos + 1 ; str[i] != 0 ; i++){        if(str[i] == 'L'){            if(node -> Left == NULL){            (node -> Left) = new(Node);            (node -> Left) -> Left  = NULL;            (node -> Left) -> Right = NULL;            (node -> Left) -> have_value = 0;            }            node = node -> Left;        }        else if(str[i] == 'R'){            if(node -> Right == NULL){             node -> Right = new(Node);            (node -> Right) -> Left  = NULL;            (node -> Right) -> Right = NULL;            (node -> Right) -> have_value = 0;            }            node = node -> Right;        }        else if(str[i] == ')'){            if(node -> have_value == 0){            node -> value =  value;            node -> have_value = 1;            }            else{            ok = 0;            }            break;        }    }}int main(){    while(scanf("%s",str) != EOF){        ok = 1;        root = new(Node);        root -> Left  = NULL;        root -> Right = NULL;        root -> have_value = 0;        BuildTree();        while(scanf("%s",str)){            if(strcmp(str,"()") == 0) break;            BuildTree();        }        int front = 0 , back = 0;        int ans[LEN];        int size = 0;        if(ok == 0) {        printf("not complete\n");        continue;        }        if(root -> have_value){            ans[size ++]  = root -> value;            array[back++] = root;            while(front < back){            Node *node = array[front++];            if(node -> Left != NULL){                 array[back++] = node -> Left;                 if((node -> Left) -> have_value == 0){                     ok = 0;                     break;                 }                 ans[size++] = (node -> Left) ->value;            }            if(node -> Right != NULL){                 array[back++] = node -> Right;                 if((node -> Right) -> have_value == 0){                     ok = 0;                     break;                 }                 ans[size++] = (node -> Right) ->value;            }        }        }        else        ok = 0;        if(ok) for(int i = 0 ; i < size; i++){            printf("%d",ans[i]);            if(i < size - 1)            printf(" ");        }        else        printf("not complete");        printf("\n");    }    return 0;}


0 0
原创粉丝点击