二叉查找树——A1043.Is it a Binary Search Tree(25)
Posted jasonpeng1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉查找树——A1043.Is it a Binary Search Tree(25)相关的知识,希望对你有一定的参考价值。
#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 ",initial[i]); } } for(int i=0;i<temppreorder.size();++i){ if(i != temppreorder.size()-1){ printf("%d",temppreorder[i]); }else{ printf("%d ",temppreorder[i]); } }*/ /*for(int i=0;i<tempMirrorder.size();++i){ if(i != tempMirrorder.size()-1){ printf("%d",tempMirrorder[i]); }else{ printf("%d ",tempMirrorder[i]); } }*/ if(order == true){ printf("YES "); 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 "); 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 "); } system("pause"); return 0; }
以上是关于二叉查找树——A1043.Is it a Binary Search Tree(25)的主要内容,如果未能解决你的问题,请参考以下文章
1043 Is It a Binary Search Tree
PAT 1043 Is It a Binary Search Tree (25分) 由前序遍历得到二叉搜索树的后序遍历
1043 Is It a Binary Search Tree (25 分)难度: 中 / 知识点: 构造二叉搜索树(BST)
1043 Is It a Binary Search Tree (25分)