1043 Is It a Binary Search Tree (25 分)(二叉查找树)
#include<bits/stdc++.h> using namespace std; typedef struct node; typedef node *tree; struct node { int data; tree L,R; }; void Insert(tree &bt,int x) { if(bt==NULL){ bt=new node; bt->data=x; bt->L=NULL; bt->R=NULL; return; } if(x<bt->data) Insert(bt->L,x); else Insert(bt->R,x); } vector<int>pre1,pre2,post1,post2; void preorder1(tree bt,vector<int>&p) { if(bt){ p.push_back(bt->data); preorder1(bt->L,p); preorder1(bt->R,p); } } void preorder2(tree bt,vector<int>&p) { if(bt){ p.push_back(bt->data); preorder2(bt->R,p); preorder2(bt->L,p); } } void postorder1(tree bt,vector<int>&p) { if(bt){ postorder1(bt->L,p); postorder1(bt->R,p); p.push_back(bt->data); } } void postorder2(tree bt,vector<int>&p) { if(bt){ postorder2(bt->R,p); postorder2(bt->L,p); p.push_back(bt->data); } } int main() { int n; scanf("%d",&n); tree bt; bt=NULL; vector<int>tt; for(int i=0;i<n;i++){ int x; scanf("%d",&x); tt.push_back(x); Insert(bt,x); } preorder1(bt,pre1); preorder2(bt,pre2); postorder1(bt,post1); postorder2(bt,post2); if(tt==pre1){ puts("YES"); for(int i=0;i<post1.size();i++){ if(i) printf(" "); printf("%d",post1[i]); } } else if(tt==pre2){ puts("YES"); for(int i=0;i<post2.size();i++){ if(i) printf(" "); printf("%d",post2[i]); } } else{ puts("NO"); } return 0; }