PAT L2-004 这是二叉搜索树吗 [二叉搜索树]
这题的主要思路就是根据题目给的前序遍历构造一颗二叉搜索树和其镜像。对构造好的树前序遍历一下,判断是否与题目给的相同。如果相同,输出后序遍历即可。证明根据这个序列确定的二叉搜索树是唯一的
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <string.h> #include <cstdio> #define maxn 1005 using namespace std; struct node { int data; node *l,*r; }; int pre[maxn]; int n,p=0; int f1=0,f2=1; node* build(node *root,int v) { node *t; if(root==NULL) { t=new node; t->data=v; t->l=t->r=NULL; return t; } if(root->data > v) root->l=build(root->l,v); else root->r=build(root->r,v); return root; } node* rbuild(node *root,int v) { node *t; if(root==NULL) { t=new node; t->data=v; t->l=t->r=NULL; return t; } if(root->data <= v) root->l=rbuild(root->l,v); else root->r=rbuild(root->r,v); return root; } void judge(node *root) { if(root) { if(root->data!=pre[p++]) { f1=1; return; } else { judge(root->l); judge(root->r); } } } void DFS(node *root) { if(root==NULL) return; DFS(root->l); DFS(root->r); if(f2) { printf("%d",root->data); f2=0; } else printf(" %d",root->data); } int main() { node *root; root=NULL; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&pre[i]); root=build(root,pre[i]); } judge(root); if(f1==0) { printf("YES\n"); printf("\n"); return 0; } else { f1=0; f2=1; p=0; root=NULL; for(int i=0;i<n;i++) root=rbuild(root,pre[i]); judge(root); if(f1==0) { printf("YES\n"); DFS(root); printf("\n"); } else printf("NO\n"); } return 0; }