[pat]1110. Complete Binary Tree (25)

来源:互联网 发布:星空软件安卓版 编辑:程序博客网 时间:2024/05/01 10:33

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

自己想的思路无比复杂。还是参考的旋风小晴天的思路=_=||(http://paste.ubuntu.com/15362594/)

自己想不到用数组来简化逻辑。。。


#pragma warning(disable:4996)#include<vector>#include<algorithm>#include<iostream>#include<string>#include<queue>using namespace std;typedef struct BNODE{BNODE *l,*r;BNODE* p;int data;}BNODE;vector<int> tree(25, -1);BNODE* pArray[25] = {NULL};int main(){int n;cin>>n;for(int i = 0; i < n; i++){BNODE *p;if(!pArray[i]) {p = (BNODE*)malloc(sizeof(BNODE));p->p = NULL;p->l = NULL;p->r = NULL;p->data = i;pArray[i] = p;}else{p = pArray[i];}string a,b;cin>>a>>b;if(a != "-"){int aa;sscanf(a.c_str(), "%d", &aa);if(pArray[aa]){p->l = pArray[aa];p->l->p = p;}else{p->l = (BNODE*)malloc(sizeof(BNODE));p->l->data = aa;p->l->p = p;p->l->l = NULL;p->l->r = NULL;pArray[aa] = p->l;}}else{p->l = NULL;}if(b != "-"){int bb;sscanf(b.c_str(), "%d", &bb);if(pArray[bb]){p->r = pArray[bb];p->r->p = p;}else{p->r = (BNODE*)malloc(sizeof(BNODE));p->r->data = bb;p->r->p = p;p->r->l = NULL;p->r->r = NULL;pArray[bb] = p->r;}}else{p->r = NULL;}}BNODE* root = pArray[0];while(root->p) root = root->p;queue<BNODE*> q;q.push(root);int num = 0;while(!q.empty()){BNODE* p = q.front();q.pop();num++;if(p){ tree[num] = p->data;q.push(p->l);q.push(p->r);}}bool f = true;for(int i = 1; i <= n; i++){if(tree[i] < 0){f =false;break;}}if(f){cout<<"YES "<<tree[n]<<endl;}else{cout<<"NO "<<tree[1]<<endl;}system("pause");return 0;}


0 0
原创粉丝点击