知识点:二叉树遍历
这个题刘汝佳的代码写的很巧妙,但是我看了一眼看不懂就先不看了,用的笨方法做的,刘汝佳的方法过段时间再看
这个题可以抽象成一个二叉树的模型,每个节点储存的数据有四个,就是输入的四个数据,然后我们设计一个递归函数,返回这个子树的重量,返回之前比较一下这个子树两边是不是平衡的,只要有一个不平衡那就是NO,
#include <bits/stdc++.h>
using namespace std;
struct node {
int wl, dl, wr, dr;
int lchild, rchild;
node() {}
node(int a, int b, int c, int d, int e, int f) {
wl = a; dl = b; wr = c; dr = d; lchild = e; rchild = f;
}
} tree[10005];
int tot;
bool flag;
int create() {
int wl, dl, wr, dr;
cin >> wl >> dl >> wr >> dr;
int root = ++tot;
tree[root] = node(wl, dl, wr, dr, -1, -1);
if (!wl) tree[root].lchild = create();
if (!wr) tree[root].rchild = create();
return root;
}
int solve(int root) {
int w1 = tree[root].wl;
if (tree[root].lchild != -1) w1 += solve(tree[root].lchild);
int w2 = tree[root].wr;
if (tree[root].rchild != -1) w2 += solve(tree[root].rchild);
if (w1 * tree[root].dl != w2 * tree[root].dr) flag = false;
return w1 + w2;
}
int main() {
int T;
cin >> T;
while (T--) {
tot = 0;
flag = true;
int root = create();
int tmp = solve(root);
cout << (flag ? "YES" : "NO") << endl;
if (T) cout << endl;
}
return 0;
}