#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include <map>
#define LL long long
using namespace std;
struct node{
int data;//數據域
node *left, *right;//指針域
};
//爲了能修改節點,需要傳引用
void Insert(node*& root, int x){
if(root == NULL){//邊界條件,沒找到即爲插入位置
root = new node;
root->data = x;
root->left = root->right = NULL;
return;//別忘了返回!~
}
if(root->data > x)
Insert(root->left, x);
else
Insert(root->right, x);
}
//先序遍歷,結果存在vi
void preOrder(node* root, vector<int>&vi){
if(root == NULL) return;
vi.push_back(root->data);
preOrder(root->left, vi);
preOrder(root->right, vi);
}
//鏡像樹先序遍歷,結果存在vi
void preOrderMirror(node* root, vector<int>&vi) {
if(root == NULL) return;
vi.push_back(root->data);
preOrderMirror(root->right, vi);
preOrderMirror(root->left, vi);
}
void postOrder(node* root, vector<int>&vi){
if(root == NULL) return;
postOrder(root->left, vi);
postOrder(root->right, vi);
vi.push_back(root->data);
}
void postOrderMirror(node* root, vector<int>&vi){
if(root == NULL) return;
postOrderMirror(root->right, vi);
postOrderMirror(root->left, vi);
vi.push_back(root->data);
}
vector<int> origin, pre, preM, post, postM;
int main(){
int n;
scanf("%d", &n);
node* root = NULL;//定義頭結點
for(int i = 0; i < n; i++){
int x;
scanf("%d", &x);
Insert(root, x);
origin.push_back(x);
}
preOrder(root, pre);
preOrderMirror(root, preM);
postOrder(root, post);
postOrderMirror(root, postM);
if(pre == origin){
printf("YES\n");
for(int i = 0; i < post.size(); i++){
if(i) printf(" ");
printf("%d", post[i]);
}
}
else if(preM == origin){
printf("YES\n");
for(int i = 0; i < postM.size(); i++){
if(i) printf(" ");
printf("%d", postM[i]);
}
}
else printf("NO\n");
return 0;
}
PAT甲級 1043 Is It a Binary Search Tree (二叉查找樹)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.