uva839 Not so Mobile (重建二叉树)
来源:互联网 发布:美洽电脑软件下载 编辑:程序博客网 时间:2024/04/29 16:52
题意:天平的平衡条件 Wl * Dl == Wr * Dr。 题目给出的是 二叉树天平, 平衡条件是所有天平都要平衡。 大天平的W 是小天平两边的W总和(很明显嘛~ 不行你就受力分析下啊)。
思路:好了, 这题就无法逃脱建树的命运了。 递归建树, 然后递归判断是否平衡。每次读入一行, 如果Wl == 0, 则递归建左子树, 如果Wr == 0, 则递归建右子树。 判断的时候, 如果Wl == 0, 则递归判断左子树, 并返回左子树(左天平)的w。 右边也一样。 然后 判断 Wl * Dl == Wr * Dr。
算法复杂度:建树o(N)+ 判断o(N)+delete结点o(N) == o(3N) , 故算法复杂度为o(N)。 N为结点数。
代码:
#include <cstdio>#include <cstring>using namespace std;#define LINE_NUM 4struct Node{int Wl;int Dl;int Wr;int Dr;Node *left;Node *right;};bool ok;Node *mkTree();void rmTree(Node *&);int judge(Node *);// judge and get weightint main(){int cases;scanf("%d", &cases);for (int css = 1; css <= cases; css++){// initNode *root = NULL;ok = true;// make treeroot = mkTree();// judgeif (css != 1) {printf("\n");}judge(root);if (ok) {printf("YES\n");} else {printf("NO\n");}// remove nodermTree(root);}return 0;}Node *mkTree(){Node *root = new Node;scanf("%d%d", &root->Wl, &root->Dl);scanf("%d%d", &root->Wr, &root->Dr);if (root->Wl == 0) {root->left = mkTree();} else {root->left = NULL;}if (root->Wr == 0) {root->right = mkTree();} else {root->right = NULL;}return root;}void rmTree(Node *&root){if (root == NULL) {return;} else {rmTree(root->left);rmTree(root->right);delete root;root = NULL;}}int judge(Node *cur){if (!ok) {return 0;}if (cur->Wl == 0) {cur->Wl = judge(cur->left);}if (cur->Wr == 0) {cur->Wr = judge(cur->right);}if (cur->Wl * cur->Dl != cur->Wr * cur->Dr) {ok = false;}return (cur->Wl + cur->Wr);}
- uva839 Not so Mobile (重建二叉树)
- UVA839 Not so Mobile【二叉树】【递归】
- uva839-Not so Mobile-二叉树的DFS
- UVA839 - Not so Mobile
- UVA839 - Not so Mobile
- UVa839 Not so Mobile
- uva839 not so mobile
- UVA839 - Not so Mobile
- uva839 Not so Mobile
- UVa839-Not So Mobile
- UVa839-Not so Mobile (天平)
- Not so Mobile 天平 UVA839
- uva839 Not so Mobile 递归
- 例题6-9 UVa839 Not so Mobile(树)
- Uva839——Not so Mobile
- Uva839 Not so Mobile(天平)
- 【DFS】UVa839 天平(Not so Mobile)
- Uva839 Not so Mobile 【递归输入】【例题6-9】
- 多声道音频数据和 WAVE 文件
- do while(FLASE)的妙用【转】
- hdu 4602题解
- 针对乐视网的主页无法打开的解决办法
- HDU--杭电--2191--悼念512汶川大地震遇难同胞——珍惜现在,感恩生活--背包
- uva839 Not so Mobile (重建二叉树)
- 在matlab中使用矩阵拟合2维函数
- ListView item设置间距无效问题
- android基础篇------------java基础(4) (面向对象程序设计)
- 认识js中的function和this
- 飞跃的心
- poj3667 线段树+区间合并
- ACM 动态规划初步 Partitioning by Palindromes
- hdu 2013 蟠桃记