0
点赞
收藏
分享

微信扫一扫

数据结构与算法题目集(中文) - 7-28 搜索树判断(25 分)

M4Y 2022-05-23 阅读 56


题目链接:​​点击打开链接​​

题目大意:略。

解题思路:略。

AC 代码

#include<bits/stdc++.h>
#include<cmath>

#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f

using namespace std;

typedef long long ll;
typedef struct node * Node;

struct node
{
int num;
Node l,r;
};

int a[1010],rs,len;

Node insert(Node head,Node tmp)
{
if(!head) return tmp;
if(tmp->num<head->num) head->l=insert(head->l,tmp);
else head->r=insert(head->r,tmp);

return head;
}

void DLR(Node h)
{
if(rs&&h)
{
if(h->num!=a[len++]) rs=0;
DLR(h->l);
DLR(h->r);
}
}

void LRD(Node h)
{
if(h)
{
LRD(h->l);
LRD(h->r);
if(rs) rs=0;
else printf(" ");
printf("%d",h->num);
}
}

void swap(Node h) // 类似 LRD
{
if(h)
{
swap(h->l);
swap(h->r);
Node tmp=h->l;
h->l=h->r;
h->r=tmp;
}
}

int main()
{
int n,b;
while(~scanf("%d",&n))
{
Node head=NULL;
for(int i=0;i<n;i++)
{
Node tmp=(Node)malloc(sizeof(node));
scanf("%d",&tmp->num);
a[i]=tmp->num;
tmp->l=tmp->r=NULL;
head=insert(head,tmp);
}

len=0;
rs=1;
DLR(head);
if(!rs)
{
swap(head);
len=0; rs=1;
DLR(head);
}

if(rs)
{
puts("YES");
LRD(head);
puts("");
}
else puts("NO");
}

return 0;
}


举报

相关推荐

0 条评论