pat-A1043:Is it a Binary Search Tree(二叉搜尋樹和及其映象樹的遍歷)
阿新 • • 發佈:2018-11-12
目錄
題目地址:https://pintia.cn/problem-sets/994805342720868352/problems/994805440976633856
題目解釋:
給出一個二叉樹的序列,判斷它是否是“二叉搜尋樹(BST)”或者“二叉搜尋樹的映象樹”的先序序列。
是的話輸出YES和該樹的後序序列,否輸出NO。
所謂映象樹就是把BST的每個結點的左右子樹交換位置,也就是對於原二叉樹來說,向下遍歷時要先遍歷每個結點的右子樹再遍歷該結點的左子樹,這樣遍歷出來的序列就是映象樹的先序序列。
解題思路:
將輸入的序列建BST樹,再按分別按BST和the mirror of BST的先序遍歷和後序遍歷方法遍歷已建好的樹,比較題目給出的序列時哪種樹的先序序列,再輸出該樹的後序序列。
注意:將先序和後序遍歷的結果用四個vector存,再直接判相等關係,若是用陣列存的話,那麼判斷相等關係時需要用到迴圈,比較費時。
vector為變長陣列,比較節省空間
對於vector中存的時內建型別的資料,如int,char,因為vector已經過載了“==” 、“!=”、 “<=”、 “>=”、 “<”、 “>”運算子,所以可以直接將兩個vector用這些運算子比較。
詳情參考:https://www.jianshu.com/p/51225ce0b234
ac程式碼:
#include <iostream> #include <cstring> #include <algorithm> #include <queue> #include <vector> using namespace std; struct node{ int data; node *left,*right; }; void insert(node *&root,int data) { if(root==NULL)//插入位置 { root=new node; root->data=data; root->left=root->right=NULL; return ; } if(data<root->data) insert(root->left,data); else insert(root->right,data); } void preorder(node *root,vector<int> &a) { if(root==NULL) return ; a.push_back(root->data); preorder(root->left,a); preorder(root->right,a); } void preordermirror(node *root,vector<int> &a)//映象樹遍歷右子樹,再遍歷左子樹 { if(root==NULL) return ; a.push_back(root->data); preordermirror(root->right,a); preordermirror(root->left,a); } void postorder(node *root,vector<int> &a) { if(root==NULL) return ; postorder(root->left,a); postorder(root->right,a); a.push_back(root->data); } void postordermirror(node *root,vector<int> &a) { if(root==NULL) return ; postordermirror(root->right,a); postordermirror(root->left,a); a.push_back(root->data); } vector<int> origin,pre,prem,post,postm; int main() { int n,data; node *root=NULL;//定義頭結點並初始化 scanf("%d",&n);//結點個數 for(int i=0;i<n;i++) { scanf("%d",&data); origin.push_back(data); insert(root,data);//建樹 } preorder(root,pre); preordermirror(root,prem); postorder(root,post); postordermirror(root,postm); if(origin==pre) { printf("YES\n"); for(int i=0;i<post.size();i++) { printf("%d",post[i]); if(i<post.size()-1) printf(" "); } } else if(origin==prem)//初始序列等於映象樹先序序列 { printf("YES\n"); for(int i=0;i<postm.size();i++) { printf("%d",postm[i]); if(i<postm.size()-1) printf(" "); } } else printf("NO\n"); return 0; }