ZOJ-1167-Trees on the Level
Posted angel-demon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ZOJ-1167-Trees on the Level相关的知识,希望对你有一定的参考价值。
题解:
我的解法是用一个类似字典树结构的结构体来表示节点。看到另一种解法是用数组来映射二叉树的,开到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] != ‘