1110. Complete Binary Tree (25)

来源:互联网 发布:python numpy range 编辑:程序博客网 时间:2024/05/21 09:44

传送门://https://www.patest.cn/contests/pat-a-practise/1110

312比赛的时候 由于读入方式有错  看到2个 - - 就用char来接收 导致3个测试点过不去,后来改正确后顺利AC

AC 代码

#include <iostream>#include <vector>#include <map>#include <unordered_map>#include <set>#include <algorithm>#include <string>#include <string.h>#include <cstdio>#include <queue>#include <stack>#include <limits>using namespace std;struct Node{    int no;    Node *parent,*left,*right;    Node():parent(NULL),left(NULL),right(NULL){};};int main(){    int n;    scanf("%d",&n);    vector<Node *>tree;    string a,b;    for(int i=0;i<n;++i)        tree.push_back(new Node());    for(int i=0;i<n;++i){        cin>>a>>b;        tree[i]->no = i;        if(a[0]!='-'){            int x;            sscanf(a.c_str(),"%d",&x);            tree[x]->parent = tree[i];            tree[i]->left = tree[x];        }        if(b[0]!='-'){            int x;            sscanf(b.c_str(),"%d",&x);            tree[x]->parent = tree[i];            tree[i]->right = tree[x];        }    }    Node *root = NULL;    for(int i=0;i<n;++i){        if(tree[i]->parent == NULL){            root = tree[i];            break;        }    }    queue<Node *>q;    vector<int>ans;    if(root){        q.push(root);        ans.push_back(root->no);    }    while(!q.empty()){        Node * p = q.front();        q.pop();        if(p->left){            q.push(p->left);            ans.push_back(p->left->no);        }else            break;        if(p->right){            q.push(p->right);            ans.push_back(p->right->no);        }else            break;    }    if(ans.size()==n){        printf("YES %d\n",ans.back());    }else        printf("NO %d\n",ans[0]);    return  0;}


0 0
原创粉丝点击