#include<stdio.h>
#include<math.h>
#include<Windows.h>
#include<stdlib.h>
typedef struct Node* Tree;
struct Node
{
int key;
Tree left;
Tree right;
bool red;
};
int preorder[30];
Tree construct(int start, int end, bool &isRBT)
{
if (start > end) return NULL;
Tree T = (Tree)malloc(sizeof(Node));
T->left = T->right = NULL;
int key = preorder[start];
if (key < 0)
{
T->key = -key;
T->red = true;
}
else
{
T->key = key;
T->red = false;
}
int index;
for (index = start; index <= end; index++)
{
if (abs(preorder[index]) > abs(key))
{
break;
}
}
T->left = construct(start + 1, index - 1, isRBT);
T->right = construct(index, end, isRBT);
if (T->red == true && ((T->left != NULL&&T->left->red == true) || (T->right != NULL&&T->right->red == true)))
{
isRBT = false;
}
return T;
}
int DFS(Tree T, bool &isRBT)
{
if (T == NULL)
{
return 1;
}
int leftSum, rightSum;
if (T->red == true)
{
leftSum = DFS(T->left, isRBT);
rightSum = DFS(T->right, isRBT);
}
if (T->red == false)
{
leftSum = 1 + DFS(T->left, isRBT);
rightSum = 1 + DFS(T->right, isRBT);
}
if (leftSum != rightSum)
{
isRBT = false;
return -1;
}
else
{
return leftSum;
}
}
int main()
{
int K;
scanf("%d", &K);
for (int i = 0; i < K; i++)
{
// input
int N;
scanf("%d", &N);
for (int j = 0; j < N; j++)
{
scanf("%d", &preorder[j]);
}
// construct a Tree
bool isRBT = true;
Tree T = construct(0, N - 1, isRBT);
// judge it is a red-black tree
// condition 1 The root is black.
if (T->red == true)
{
printf("No\n");
continue;
}
// condition 2 If a node is red, then both its children are black.
if (isRBT == false)
{
printf("No\n");
continue;
}
// condition 3 For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
DFS(T, isRBT);
if (isRBT == false)
{
printf("No\n");
}
else
{
printf("Yes\n");
}
}
return 0;
}