九度OJ-題目1009:二叉搜尋樹
阿新 • • 發佈:2018-12-24
題目1009:二叉搜尋樹
從現在開始打算重啟刷題征程。程式設計師的人生不需要解釋!
這次撇開poj hoj等難度較大的oj系統,從九度入手(已經很長時間沒寫過程式碼了),主要先“叫醒” 沉睡依舊的大腦。唉~真的很長時間沒寫部落格,沒寫程式碼了,只能加油吧!
題目如下
時間限制:1 秒
記憶體限制:32 兆
特殊判題:否
提交:4310
解決:1921
- 題目描述:
- 判斷兩序列是否為同一二叉搜尋樹序列
- 輸入:
-
開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。
接下去一行是一個序列,序列長度小於10,包含(0~9)的數字,沒有重複數字,根據這個序列可以構造出一顆二叉搜尋樹。
接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉搜尋樹。
- 輸出:
-
如果序列相同則輸出YES,否則輸出NO
- 樣例輸入:
-
2 567432 543267 576342 0
- 樣例輸出:
-
YES NO
題目難度:水題
解題思路:
1.構建二叉排序樹。(題目中叫做二叉搜尋樹,其時是一樣的,就是對於二叉樹的任何一個結點的所有左孩子結點都小於父結點,但是父節點都小於右孩子結點,好吧,我既然還能記得住,看來,大腦鏽的不是很厲害)
2.對構建的二叉排序樹盡心前序遍歷,得到前序序列。(前序就是 前根序,後序就是 後根序,中序就是 中根序)
3.比較前根序列,一樣就輸出YES ,不一樣就輸出 NO
c++程式碼:
#include <iostream> #include <string.h> using namespace std; struct Node{ Node* left ; Node* right ; char data ; Node():left(NULL),right(NULL),data('*'){} }; //插入有序樹 void insertSortTree(Node * root, char data){ Node * p = root ; Node * q = new Node ; q->data = data ; while(1){ if(p->data>data&&p->left)p=p->left; else if(p->data<data&&p->right)p=p->right; else if(p->data>data){ p->left = q ; return; } else if(p->data<data){ p->right = q ; return; } } } //銷燬有序樹 void destroySortTree(Node * root){ Node * p = root ; if(p->left!=NULL)destroySortTree(p->left); if(p->right!=NULL)destroySortTree(p->right); delete p ; } //建立有序樹 Node * createSortTree(char * datas , int n){ if(n<=0)return NULL; Node * root = new Node ; root->data = datas[0]; Node * p = root ; for(int i = 1 ; i < n ;i++){ insertSortTree(root,datas[i]); } return root ; } //用到的變數 char x1[11];int ct1 = 0; char x2[11];int ct2 = 0; //前根序遍歷 void pre_lst(Node * root,char* x,int* index){ if(root)x[(*index)++] = root->data ; if(root->left)pre_lst(root->left,x,index) ; if(root->right)pre_lst(root->right,x,index) ; } //比較前根序列 bool cmp(int n){ for(int i = 0 ; i < n ; i++){ if(x1[i]!=x2[i])return false; } return true ; } int main() { int T ; int n; Node * root1 = NULL; Node * root2 = NULL; int index1 ,index2 ; while(1){ cin>>T ;if(T==0)break; cin>>x1 ; ct1 = strlen(x1); root1 = createSortTree(x1,ct1); index1 = 0 ; pre_lst(root1,x1,&index1) ; for(int i = 0 ; i < T ; i++ ){ cin>>x2 ; ct2 = strlen(x2); root2 = createSortTree(x2,ct2); index2 = 0 ; pre_lst(root2,x2,&index2) ; if(cmp(ct1)){ cout<<"YES"<<endl; }else cout<<"NO"<<endl; destroySortTree(root2) ; } destroySortTree(root1) ; } return 0; }
好了,寫程式碼的感覺來了。