这个题直接没读懂,看了柳神的代码后自己照葫芦画瓢写了。还是有几个点没有搞懂。等二刷再来看看。
#include <bits/stdc++.h>
using namespace std;
struct tree {
int v;
tree *lc, *rc;
};
vector<int> arr;
tree *bulid (tree *root, int v) {
if (root == NULL) {
root = new tree();
root->lc = root->rc = NULL;
root->v = v;
}
else if (abs(v) > abs(root->v))
root->rc = bulid (root->rc, v);
else
root->lc = bulid (root->lc, v);
return root;
}
bool judge1 (tree *root) {
if (root == NULL) return true;
if (root->v < 0) { //这里自己写的是大于>,下面也是换成大于的,但是测试点3、4过不去
//这里写成大于,如果根节点是负数,下一层是正数,返回的是true,但是下面判断arr[0] > 0应该不影响的啊
if (root->lc != NULL && root->lc->v < 0) return false;
if (root->rc != NULL && root->rc->v < 0) return false;
}
return judge1(root->lc) && judge1(root->rc);
}
int getNum (tree *root) {
if (root == NULL) return 0;
int l = getNum (root->lc);
int r = getNum (root->rc);
return root->v > 0 ? max(l, r) + 1 : max(l, r);
}
bool judge2 (tree *root) {
if (root == NULL) return true;
int l = getNum (root->lc);
int r = getNum (root->rc);
if (l != r) return false;
return judge2(root->lc) && judge2(root->rc);
}
int main() {
int n, k;
scanf ("%d", &n);
for (int i = 0; i < n; i++) {
tree *root = NULL;
scanf ("%d", &k);
arr.resize(k);
for (int j = 0; j < k; j++) {
scanf ("%d", &arr[j]);
root = bulid (root, arr[j]);
}
if (arr[0] > 0 && judge1(root) == true && judge2(root) == true)
printf ("Yes\n");
else
printf ("No\n");
}
}