#include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <queue> using namespace std; struct node{ int data; node *left; node *right; }; void insert(node* &root,int data){ if(root == NULL){ root = new node; root->data = data; root->left = NULL; root->right = NULL; } else if(data < root->data){ insert(root->left,data); }else{ insert(root->right,data); } } void preOrder(node* root,vector<int>& temppreorder){ if(root == NULL){ return; } temppreorder.push_back(root->data); preOrder(root->left,temppreorder); preOrder(root->right,temppreorder); } void preMirro(node* root,vector<int>& tempMirrorder){ if(root == NULL){ return; } tempMirrorder.push_back(root->data); preMirro(root->right,tempMirrorder); preMirro(root->left,tempMirrorder); } void postOrder(node* root,vector<int>& postorder){ if(root == NULL){ return; } postOrder(root->left,postorder); postOrder(root->right,postorder); postorder.push_back(root->data); } void postMirrOrder(node* root,vector<int>& postMirrorder){ if(root == NULL){ return; } postMirrOrder(root->right,postMirrorder); postMirrOrder(root->left,postMirrorder); postMirrorder.push_back(root->data); } int main(){ int n; vector<int> initial,postorder,postMirrorder; vector<int> temppreorder; vector<int> tempMirrorder; scanf("%d",&n); node *root = NULL; int t; for(int i =0;i<n;++i){ scanf("%d",&t); initial.push_back(t); insert(root,t); } preOrder(root,temppreorder); preMirro(root,tempMirrorder); bool order = true,mirrOrder = true; for(int i = 0;i<initial.size();++i){ if(initial[i] != temppreorder[i]){ order = false; } if(initial[i] != tempMirrorder[i]){ mirrOrder = false; } } /* for(int i=0;i<initial.size();++i){ if(i != initial.size()-1){ printf("%d",initial[i]); }else{ printf("%d\n",initial[i]); } } for(int i=0;i<temppreorder.size();++i){ if(i != temppreorder.size()-1){ printf("%d",temppreorder[i]); }else{ printf("%d\n",temppreorder[i]); } }*/ /*for(int i=0;i<tempMirrorder.size();++i){ if(i != tempMirrorder.size()-1){ printf("%d",tempMirrorder[i]); }else{ printf("%d\n",tempMirrorder[i]); } }*/ if(order == true){ printf("YES\n"); postOrder(root,postorder); for(int i = 0;i<postorder.size();++i){ if(i != postorder.size()-1){ printf("%d ",postorder[i]); }else{ printf("%d",postorder[i]); } } } else if(mirrOrder == true){ printf("YES\n"); postMirrOrder(root,postMirrorder); for(int i = 0;i<postMirrorder.size();++i){ if(i != postMirrorder.size()-1){ printf("%d ",postMirrorder[i]); }else{ printf("%d",postMirrorder[i]); } } }else{ printf("NO\n"); } system("pause"); return 0; }
原文地址:https://www.cnblogs.com/JasonPeng1/p/12240010.html
时间: 2024-11-05 16:09:22