Two days ago,I submitted the code but it wasn’t accepted.Then I spent a lot of time to change it and finally it ac!
Note: the simple path in Property 5 means that path from each node to NULL! (that is the leaf!You can get this from property 3).In my previous code,I didn’t consider that ,so my dfs function(p5()) is not correct.(e.g. when the preorder traversal sequence is 1 2,it should print “No”,but if you ignored this point it would print “Yes”).
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <unordered_map>
#include <set>
using namespace std;
int pre[50];
int K, N;
typedef struct Node {
int Data;
Node* right;
Node* left;
int cnt;
};
bool f4; //性质4的判断
bool f5;
Node* insert(Node *T, int k)
{
if (T == NULL)
{
T = (Node*)malloc(sizeof(Node));
T->Data = k;
T->left = NULL;
T->right = NULL;
T->cnt = -1;
}
else {
if (abs(k) > abs(T->Data))
{
if (f4&&T->right == NULL && T->Data < 0 && k < 0) f4 = false;
T->right = insert(T->right, k);
}
else {
if (f4&&T->left == NULL && T->Data < 0 && k < 0) f4 = false;
T->left = insert(T->left, k);
}
}
return T;
}
Node* create(int *pre, int N)
{
Node * rt = (Node*)malloc(sizeof(Node));
rt->Data = pre[0];
rt->right = rt->left = NULL;
rt->cnt = -1;
for (int i = 1; i < N; i++)
{
rt = insert(rt, pre[i]);
}
return rt;
}
void p5(Node *T)
{
if (!T->left) {
int tc;
if (T->Data > 0) tc = 2;
else tc = 1;
if (T->cnt == -1)T->cnt = tc;
else if (T->cnt != tc) f5 = false;
}else{
if (T->Data < 0 && T->left->Data < 0) f4 = false;
p5(T->left);
int tc;
if (T->Data > 0)tc = T->left->cnt + 1;
else tc = T->left->cnt;
if (T->cnt == -1)T->cnt = tc;
else if (T->cnt != tc) f5 = false;
}
if (!T->right) {
int tc;
if (T->Data > 0) tc = 2;
else tc = 1;
if (T->cnt == -1)T->cnt = tc;
else if (T->cnt != tc) f5 = false;
}else {
if (T->Data < 0 && T->right->Data < 0) f4 = false;
p5(T->right);
int tc;
if (T->Data > 0) tc = T->right->cnt + 1;
else tc = T->right->cnt;
if (T->cnt == -1) T->cnt = tc;
else if (T->cnt != tc) f5 = false;
}
}
void DelTree(Node **T)
{
if(*T == NULL) return;
DelTree(&(*T)->left);
DelTree(&(*T)->right);
delete *T;
*T = 0;
}
int main() {
cin >> K;
while (K--)
{
f4 = true;
f5 = true;
cin >> N;
for (int i = 0; i < N; i++) cin >> pre[i];
if (pre[0] < 0)printf("No\n");
else {
Node* T = create(pre, N);
p5(T);
if (f4&&f5) printf("Yes\n");
else printf("No\n");
DelTree(&T);
}
}
return 0;
}
Last but not least it’s better to delete the tree after we judge it.