5-4 是否同一棵二叉搜索树 (25分)
https://pta.patest.cn/pta/test/15/exam/4/question/712
這道題考察二叉搜索樹的實(shí)現(xiàn),并且還需要一定的邏輯與算法,所以題目還是挺好的。
?
5-4?是否同一棵二叉搜索樹???(25分)
給定一個(gè)插入序列就可以唯一確定一棵二叉搜索樹。然而,一棵給定的二叉搜索樹卻可以由多種不同的插入序列得到。例如分別按照序列{2, 1, 3}和{2, 3, 1}插入初始為空的二叉搜索樹,都得到一樣的結(jié)果。于是對(duì)于輸入的各種插入序列,你需要判斷它們是否能生成一樣的二叉搜索樹。
輸入格式:
輸入包含若干組測(cè)試數(shù)據(jù)。每組數(shù)據(jù)的第1行給出兩個(gè)正整數(shù)NN?(\le 10≤10)和LL,分別是每個(gè)序列插入元素的個(gè)數(shù)和需要檢查的序列個(gè)數(shù)。第2行給出NN個(gè)以空格分隔的正整數(shù),作為初始插入序列。最后LL行,每行給出NN個(gè)插入的元素,屬于LL個(gè)需要檢查的序列。
簡(jiǎn)單起見,我們保證每個(gè)插入序列都是1到NN的一個(gè)排列。當(dāng)讀到NN為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這道題首先是需要建立一個(gè)二叉搜索樹,感覺雖然這個(gè)簡(jiǎn)單,但把這個(gè)代碼寫的清晰,清爽,還是不太容易的,需要自己理清整個(gè)思路,然后才能寫好這個(gè)代碼。
然后就是這個(gè)搜索過程。給一個(gè)標(biāo)記,然后建好一棵樹后,掃描這棵樹,如果用給定的測(cè)試來(lái)掃描這顆樹,在每個(gè)點(diǎn)出現(xiàn)之前的所有點(diǎn),都被掃描過,則符合題意。
最后要注意,要復(fù)原整個(gè)標(biāo)記值,否則會(huì)讓上一圈的循環(huán)對(duì)這一圈造成影響。
代碼如下(只有參考了ppt,才能寫出如此清爽的代碼~)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<queue>
using namespace std;
struct node
{
int num;
struct node * left;
struct node * right;
int flag;
};
typedef struct node * tree;
tree newnode(int n1)
{
tree t=(tree)malloc(sizeof(struct node));
t->num=n1;
t->left=NULL;
t->right=NULL;
t->flag=0;
return t;
}
tree Insert(tree t,int n)
{
if(!t)
t=newnode(n);
else
{
if(n>t->num)
{
t->right=Insert(t->right,n);
}
else
t->left=Insert(t->left,n);
}
return t;
}
tree maketree(int n)
{
tree t;
int this_num;
scanf("%d",&this_num);
t=newnode(this_num);
for(int i=1;i<n;i++)
{
scanf("%d",&this_num);
t=Insert(t,this_num);
}
return t;
}
int check(tree t,int v)
{
if(t->flag)
{
if(v>t->num)
{
return check(t->right,v);
}
else if(v<t->num)
{
return check(t->left,v);
}
}
else
{
if(v==t->num)
{
t->flag=1;
return 1;
}
else
return 0;
}
}
int judge(tree t,int n)
{
int flag=0;
int this_num;
scanf("%d",&this_num);
if(this_num!=t->num)
flag=1;
else
t->flag=1;
for(int i=1;i<n;i++)
{
scanf("%d",&this_num);
if(flag==0&&check(t,this_num)==0)
flag=1;
}
if(flag)
return 1;
else
return 0;
}
void reset(tree t)
{
if(t->left) reset(t->left);
if(t->right) reset(t->right);
t->flag=0;
}
void freetree(tree t)
{
if(t->left) freetree(t->left);
if(t->right) freetree(t->right);
free(t);
}
int main()
{
int n,m;
tree t;
while(scanf("%d",&n)&&n)
{
scanf("%d",&m);
t =maketree(n);
for(int i=1;i<=m;i++)
{
if(judge(t,n))
printf("No\n");
else
printf("Yes\n");
reset(t);
}
// free(t);
}
return 0;
}
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/hyx0123/p/7268056.html
總結(jié)
以上是生活随笔為你收集整理的5-4 是否同一棵二叉搜索树 (25分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C. The Meaningless G
- 下一篇: 找新朋友(欧拉函数)