1043 Is It a Binary Search Tree (25point(s)) Easy only once *二叉排序树
基本点:
题目繁琐无新意;
关键点:
左右节点子树交换,可以直接preorder的访问顺序就可以;
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
node* root =NULL;
vector<int>inseq;
vector<int>preseq;
vector<int>postseq;
void create(node* &root,int n) {
if (root == NULL) {
root = new node;
root->data = n;
root->lchild = root->rchild = NULL;
return;
}
if (root->data <= n)
create(root->rchild, n);
else
create(root->lchild, n);
}
void preorder(node* root) {
if (root == NULL)
return;
preseq.push_back(root->data);
preorder(root->lchild);
preorder(root->rchild);
}
void postorder(node* root) {
if (root == NULL)
return;
postorder(root->lchild);
postorder(root->rchild);
postseq.push_back(root->data);
}
bool charge(vector<int>v1, vector<int>v2) {
for (int i = 0; i < v1.size(); i++) {
if (v1[i] != v2[i])
return false;
}
return true;
}
void exchage_tree(node* root) {
if (root == NULL)
return;
exchage_tree(root->lchild);
exchage_tree(root->rchild);
node* temp = root->lchild;
root->lchild = root->rchild;
root->rchild = temp;
}
int main(){
int n;
int a;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a;
create(root,a);
inseq.push_back(a);
}
preorder(root);
if (charge(preseq, inseq)) {
//如果相同;
cout << "YES" << endl;
postorder(root);
for (int i = 0; i < postseq.size(); i++) {
if (i == 0)
cout << postseq[i];
else
cout << " " << postseq[i];
}
return 0;
}
preseq.resize(0);
postseq.resize(0);
exchage_tree(root);
preorder(root);
if (charge(preseq, inseq)) {
//镜像树如果相同;
cout << "YES" << endl;
postorder(root);
for (int i = 0; i < postseq.size(); i++) {
if (i == 0)
cout << postseq[i];
else
cout << " " << postseq[i];
}
return 0;
}
cout << "NO";
return 0;
}

浙公网安备 33010602011771号