二叉排序樹
Time Limit: 1000MS Memory limit: 65536K
題目描寫敘述
二叉排序樹的定義是:或者是一棵空樹。或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上全部結點的值均小於它的根結點的值; 若它的右子樹不空。則右子樹上全部結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。
今天我們要推斷兩序列是否為同一二叉排序樹
輸入
開始一個數n,(1<=n<=20) 表示有n個須要推斷,n= 0 的時候輸入結束。 接下去一行是一個序列。序列長度小於10,包括(0~9)的數字,沒有反復數字,依據這個序列能夠構造出一顆二叉排序樹。 接下去的n行有n個序列,每一個序列格式跟第一個序列一樣,請推斷這兩個序列能否組成同一顆二叉排序樹。(數據保證不會有空樹)
輸出
演示樣例輸入
2 123456789 987654321 432156789 0
演示樣例輸出
NO NO
依然是二叉排序樹。。定義都沒變 然後推斷兩顆樹是否為同一二叉排序樹,我是直接dfs一種先序遍歷然後看兩顆樹的先序遍歷是否同樣。。
#include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include <string> #include <cctype> #include <vector> #include <cstdio> #include <cmath> #include <deque> #include <stack> #include <map> #include <set> #define ll long long #define maxn 1010 #define pp pair<int,int> #define INF 0x3f3f3f3f #define max(x,y) ( ((x) > (y)) ?(x) : (y) ) #define min(x,y) ( ((x) > (y)) ? (y) : (x) ) using namespace std; typedef struct node { char d; node *l,*r; }*p; int n,sb; void Insert(p &T,int x) { if(T==NULL) { T=new node; T->l=NULL;T->r=NULL; T->d=x; } else { if(x<T->d) Insert(T->l,x); else Insert(T->r,x); } } void dfs(p T,char *ans) { if(T) { ans[sb++]=T->d; dfs(T->l,ans); dfs(T->r,ans); } } int main() { while(~scanf("%d",&n)&&n) { p root=NULL; char tem[12],ans[12]; scanf("%s",tem); for(int i=0;i<strlen(tem);i++) Insert(root,tem[i]); sb=0;dfs(root,ans);ans[sb]=‘\0‘; while(n--) { p troot=NULL; scanf("%s",tem); for(int i=0;i<strlen(tem);i++) Insert(troot,tem[i]); sb=0;dfs(troot,tem);tem[sb]=‘\0‘; if(!strcmp(ans,tem)) puts("YES"); else puts("NO"); } } return 0; }
二叉排序樹