# L3-1 是否完全二叉搜索树 (30分)

9
38 45 42 24 58 30 67 12 51

38 45 24 58 42 30 12 67 51
YES

8
38 24 12 45 58 67 42 51

38 45 24 58 42 12 67 51
NO

题解


#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v,TreeNode* l=NULL,TreeNode* r=NULL) :val(v),left(l),right(r) {}
};

void insert(int v,TreeNode*& root) {
if (root==NULL) {
root=new TreeNode(v);
return;
}
TreeNode* y;
TreeNode* x=root;
while (x!=NULL) {
y=x;
if (v>x->val) {
x=x->left;
}
else {
x=x->right;
}
}
if (v>y->val) {
y->left=new TreeNode(v);
}
else {
y->right=new TreeNode(v);
}
}

void bfs(TreeNode* root) {
queue<TreeNode*> q;
if (root) {
q.push(root);
}
int print=0;
while (!q.empty()) {
TreeNode* rt=q.front();
q.pop();
if (!print) {
print=1;
}
else {
putchar(' ');
}
printf("%d",rt->val);
if (rt->left) {
q.push(rt->left);
}
if (rt->right) {
q.push(rt->right);
}
}
putchar('\n');
}

int judge(TreeNode* root) {
TreeNode* p;
queue<TreeNode*> q;
q.push(root);
while ((p=q.front())!=NULL) {
q.push(p->left);
q.push(p->right);
q.pop();
}
while (!q.empty()) {
if (q.front()) {
return 0;
}
q.pop();
}
return 1;
}

int main()
{
int n,val;
TreeNode* root=NULL;
scanf("%d",&n);
for (int i=0;i<n;i++) {
scanf("%d",&val);
insert(val,root);
}
bfs(root);
printf("%s\n",judge(root)?"YES":"NO");
return 0;
}


03-27 129
01-30 197

09-07 239
03-28 59
02-23 769
10-28 549
01-29 102