//给定N个整数作为BST的结点插入顺序,如果这棵BST或镜像BST的先序等于输入顺序,则输出YES,并输出相应BST的后序,否则输出NO
//code:
#include <cstdio>
#include <vector>
using namespace std;
int N;
vector<int> origin;
vector<int> preOrder_vector;
vector<int> preOrder_mirror_vector;
int j;
struct node {
int data;
node* lChild;
node* rChild;
};
void insert(node* &root, int data) { //二叉树的每次插入,都先从root开始
if(root == NULL) {
root = new node;
root->data = data;
root->lChild = root->rChild = NULL;
return;
}
if(data >= root->data) insert(root->rChild, data); //右子树 >= 根结点
else insert(root->lChild, data);
}
void insert_mirror(node* &root,int data) {
if(root == NULL) {
root = new node;
root->data = data;
root->lChild = root->rChild = NULL;
return;
}
if(data >= root->data) insert_mirror(root->lChild, data);
else insert_mirror(root->rChild, data);
}
void preOrder(node* root, vector<int>& vi) {
if(root == NULL) return;
vi.push_back(root->data);
preOrder(root->lChild, vi);
preOrder(root->rChild, vi);
}
void preOrder_mirror(node* root, vector<int>& vi) {
if(root == NULL) return;
vi.push_back(root->data);
preOrder_mirror(root->lChild, vi);
preOrder_mirror(root->rChild, vi);
}
void postOrder(node* root) {
if(root == NULL) return;
postOrder(root->lChild);
postOrder(root->rChild);
if(j != N) {
printf("%d ",root->data);
j ++;
} else {
printf("%d",root->data);
}
}
int main() {
node* root = NULL;
node* root_mirror = NULL;
scanf("%d",&N);
for(int i=0; i<N; i++) {
int c;
scanf("%d",&c);
origin.push_back(c);
insert(root, c);
insert_mirror(root_mirror, c);
}
preOrder(root, preOrder_vector);
preOrder_mirror(root_mirror, preOrder_mirror_vector);
if(preOrder_vector == origin) { vector可以直接比较
printf("YES\n");
j = 1; //用于控制输出
postOrder(root);
} else if(preOrder_mirror_vector == origin) {
printf("YES\n");
j = 1;
postOrder(root_mirror);
} else {
printf("NO");
}
return 0;
}
1043 Is It a Binary Search Tree (25)
最新推荐文章于 2023-11-25 14:12:34 发布