标签:printf 注意 def 遍历 clu include lse create roo
发现规律,对于最左边来说,后面所有的集合都是先小后大或者先大后小,如果小大交错那么不符合
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
#define null NULL
struct node{
int value;
node* left;
node* right;
node(int _value){
value = _value;
left = null;
right = null;
}
};
int create(vector<int> nodes, int mode, node* &root){
if(nodes.size() != 0){
root = new node(nodes[0]);
}else{
return 1;
}
vector<int> left;
vector<int> right;
int i = 0;
if(mode == 1){
for(i=1;i<nodes.size();i++){
if(nodes[i] > nodes[0]){
break;
}
left.push_back(nodes[i]);
}
for(;i<nodes.size();i++){
if(nodes[i] < nodes[0]){
return 0;
}
right.push_back(nodes[i]);
}
}else{
for(i=1;i<nodes.size();i++){
if(nodes[i] < nodes[0]){
break;
}
left.push_back(nodes[i]);
}
for(;i<nodes.size();i++){
if(nodes[i] > nodes[0]){
return 0;
}
right.push_back(nodes[i]);
}
}
int res1 = create(left, mode, root->left);
int res2 = create(right, mode, root->right);
return res1 & res2;
}
void post(node* root, int level){
if(root == null){
return ;
}
post(root->left, level+1);
post(root->right, level+1);
if(level == 0){
printf("%d", root->value);
}else{
printf("%d ", root->value);
}
}
int main() {
int N;
vector<int> nodes;
scanf("%d", &N);
for(int i=0;i<N;i++){
int v;
scanf("%d", &v);
nodes.push_back(v);
}
int mode = 0;
for(int i=1;i<nodes.size();i++){
if(nodes[i] < nodes[0]){
mode = 1;
break;
}
if(nodes[i] > nodes[0]){
mode = 2;
break;
}
}
if(mode == 0){
int i = 0;
printf("YES\n");
for(i=0;i<nodes.size()-1;i++){
printf("%d ", nodes[i]);
}
printf("%d", nodes[i]);
return 0;
}
node* root;
int res = create(nodes, mode, root);
if(res == 0){
printf("NO");
}else{
printf("YES\n");
post(root, 0);
}
}
1043 Is It a Binary Search Tree (25分)
标签:printf 注意 def 遍历 clu include lse create roo
原文地址:https://www.cnblogs.com/d-i-p/p/12393004.html