7-1 是否同一棵二叉搜索树 (30分)
生活随笔
收集整理的這篇文章主要介紹了
7-1 是否同一棵二叉搜索树 (30分)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)插入序列就可以唯一確定一棵二叉搜索樹。然而,一棵給定的二叉搜索樹卻可以由多種不同的插入序列得到。例如分別按照序列{2, 1, 3}和{2, 3, 1}插入初始為空的二叉搜索樹,都得到一樣的結(jié)果。于是對(duì)于輸入的各種插入序列,你需要判斷它們是否能生成一樣的二叉搜索樹。
輸入格式:
輸入包含若干組測(cè)試數(shù)據(jù)。每組數(shù)據(jù)的第1行給出兩個(gè)正整數(shù)N (≤10)和L,分別是每個(gè)序列插入元素的個(gè)數(shù)和需要檢查的序列個(gè)數(shù)。第2行給出N個(gè)以空格分隔的正整數(shù),作為初始插入序列。最后L行,每行給出N個(gè)插入的元素,屬于L個(gè)需要檢查的序列。
簡(jiǎn)單起見,我們保證每個(gè)插入序列都是1到N的一個(gè)排列。當(dāng)讀到N為0時(shí),標(biāo)志輸入結(jié)束,這組數(shù)據(jù)不要處理。
輸出格式:
對(duì)每一組需要檢查的序列,如果其生成的二叉搜索樹跟對(duì)應(yīng)的初始序列生成的一樣,輸出“Yes”,否則輸出“No”。
輸入樣例:
4 2 3 1 4 2 3 4 1 2 3 2 4 1 2 1 2 1 1 2 0輸出樣例:
Yes No No #include <bits/stdc++.h> #include <queue> using namespace std; struct Tree {int Ele;struct Tree *Left;struct Tree *Right; }; typedef struct Tree* T; T Insert(T root,int key); bool judge(T a,T b); void Get(T a,int *aa,int *na); bool Equal(int *a,int nn,int *b); void Print(int *a,int n); int n,L; int main() {T Sam,Test;int x;while (1){cin>>n;if (n==0){break;}cin>>L;Sam=NULL;for (int i=0;i<n;i++){cin>>x;Sam=Insert(Sam,x);}for (int i=0;i<L;i++){Test=NULL;for (int j=0;j<n;j++){cin>>x;Test=Insert(Test,x);}if (judge(Sam,Test)){printf("Yes\n");}else{printf("No\n");}}}return 0; }T Insert(T root,int key) {if (root==NULL){root=(T)malloc(sizeof(struct Tree));root->Ele=key;root->Left=root->Right=NULL;return root;}T now;if (key>root->Ele){now=Insert(root->Left,key);root->Left=now;}else if (key<root->Ele){now=Insert(root->Right,key);root->Right=now;}return root; }bool judge(T a,T b) {int aa[15],bb[15],nn;memset(aa,0,sizeof(aa));memset(bb,0,sizeof(bb));Get(a,aa,&nn);Get(b,bb,&nn); // Print(aa,nn); // Print(bb,nn);if (Equal(aa,nn,bb)){return true;}return false; }void Get (T a,int *aa,int *na) {queue<T>q;T t=NULL;*na=0;if (a==NULL){*na=-1;return;}q.push(a);while (!q.empty()){t=q.front();q.pop();aa[(*na)++]=t->Ele;if (t->Left){q.push(t->Left);}if (t->Right){q.push(t->Right);}}return; }bool Equal(int *a,int nn,int *b) {for (int i=0;i<nn;i++){if (a[i]!=b[i]){return false;}}return true; }void Print(int *a,int n) {printf("\n");for (int i=0;i<n;i++){printf("%d ",a[i]);}printf("\n"); }總結(jié)
以上是生活随笔為你收集整理的7-1 是否同一棵二叉搜索树 (30分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第二章 数据的表示和运算 2.1.2 B
- 下一篇: Leetcode--24. 两两交换链表