标签:i++ 结果 stat line ace 初始 ++ complete memory
题解:
我的解法是用一个类似字典树结构的结构体来表示节点。看到另一种解法是用数组来映射二叉树的,开到14000就过了,但是我觉得是数据水了,因为题中说最多 256个节点,如果256个节点连成链型,除根节点外每个节点都是父节点的右儿子。那么数组要开pow(2, 256)个。可见这种方法是不可行的;
Accepted | 1167 | C++ | 0 | 280 |
#include "cstdio" #include "cstring" #include "cstdlib" #include "cctype" #include "queue" #include "vector" using namespace std; struct Tree { int data; Tree* lson; Tree* rson; } *root; char s[300]; // v记录遍历的结果,ok记录可否构成树 vector<int> v; bool ok; // 初始化节点 Tree* init() { Tree* point = (Tree*)malloc(sizeof(Tree)); point->data = 0; point->lson = point->rson = NULL; return point; } // 插入一个节点 void insert(char* s) { int _data = 0, i = 1; Tree* point = root; while (isdigit(s[i])) { _data = _data * 10 + (s[i++] ^ ‘0‘); } i++; while (s[i] != ‘)‘) { if (s[i++] == ‘L‘) { if (point->lson == NULL) { point->lson = init(); } point = point->lson; } else { if (point->rson == NULL) { point->rson = init(); } point = point->rson; } } if (point->data) { ok = false; } point->data = _data; } // 按层遍历并释放二叉树 void BFS() { queue<Tree*> q; q.push(root); Tree* point; while (!q.empty()) { point = q.front(); q.pop(); v.push_back(point->data); if (!point->data) { ok = false; } if (point->lson) { q.push(point->lson); } if (point->rson) { q.push(point->rson); } free(point); } } int main() { while (~scanf("%s", s)) { root = init(); v.clear(); ok = true; while(s[2] != ‘\0‘) { insert(s); scanf("%s", s); } BFS(); if (!ok) { puts("not complete"); continue; } printf("%d", v[0]); for (int i = 1; i < v.size(); i++) { printf(" %d", v[i]); } puts(""); } return 0; }
标签:i++ 结果 stat line ace 初始 ++ complete memory
原文地址:https://www.cnblogs.com/Angel-Demon/p/10577196.html