UVa 122 - Trees on the level
来源:互联网 发布:宝塔 递推 算法 编辑:程序博客网 时间:2024/05/18 03:30
题目:给你一颗二叉树上面的若干节点上的值(均为正数),判断从根到所有的给定的点的路径上的节点,
是不是都有值,且只被赋值一次。
分析:递归,搜索,树。
首先,利用递归建树,过程中记录是否有节点赋值两次;
然后,利用递归判断,查找是否有未被赋值的节点;
最后,利用bfs安深度输出每层的值。
说明:强大的sscanf函数╮(╯▽╰)╭。
#include <algorithm>#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>#include <cmath>using namespace std;typedef struct tnode{int V;tnode* L;tnode* R;}tree;tree node[300];tree*root;int tree_size,complete;int test(tree *root){if (!root->V) return 0;int ans = 0;if (!root->L || test(root->L))ans ++;if (!root->R || test(root->R))ans ++;return ans == 2;}void madetree(tree *root, char* str, int v){if (*str == 'R') {if (!root->R)root->R = &node[++ tree_size];madetree(root->R, str+1, v);}else if (*str == 'L') {if (!root->L)root->L = &node[++ tree_size];madetree(root->L, str+1, v);}else {if (root->V)complete = 0;root->V = v;}}tree*Q[300];void output(tree *root){int move = 0,save = 0;Q[save ++] = root;printf("%d",root->V);while (move < save) {tree* now = Q[move ++];if (now->L) {printf(" %d",now->L->V);Q[save ++] = now->L;}if (now->R) {printf(" %d",now->R->V);Q[save ++] = now->R;}}printf("\n");}int main(){char buf[256],leaf[256];int value;complete = 1;root = &node[tree_size = 0];while (~scanf("%s",buf)) {if (!strcmp(buf,"()")) {if (!complete || !test(root))printf("not complete\n");else output(root);memset(node, 0, sizeof(node));root = &node[tree_size = 0];complete = 1;}else {sscanf(buf,"(%d,%s",&value,leaf);madetree(root, leaf, value);}} return 0;}
1 0
- UVa Problem 122 - Trees on the level
- UVA 122 - Trees on the level
- uva 122 - Trees on the level
- uva 122 Trees on the level
- UVA-122-Trees on the level
- UVA - 122 Trees on the level
- UVa 122 - Trees on the level
- UVa 122 - Trees on the level
- Uva 122 Trees on the level
- UVA - 122 Trees on the level
- UVa 122 - Trees on the level
- UVA - 122 Trees on the level Map
- Uva - 122 - Trees on the level
- uva 122 - Trees on the level
- UVa 122 Trees on the level
- uva 122 Trees on the level
- UVa 122 - Trees on the level
- UVa 122 Trees on the level
- Java对象的序列化和反序列化
- 黑马程序员——集合(三)
- 2015年上半年——项目记录一
- Longest Substring Without Repeating Characters (最长不重复字符的子序列) Java-O(n)解法
- iOS经纬度获取
- UVa 122 - Trees on the level
- 1-1 RFID理论基础知识要点
- mybatis初步认识(一)
- C语言精度计算——大数相乘
- java实现屏幕捕捉程序
- tcpdump 使用
- MVC 数据库连接
- 字符串的大小写转换方法
- 静态工厂方法与构造器