R7-9 搜索树判断 (25 分)

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
    int data;
    node *left,*right;
} tree;
tree*create(tree*root,int x)
{
    if(!root)
    {
        root=new node;
        root->data=x;
        root->right=root->left=NULL;
        return root;
    }
    else
    {
        if(x<root->data)
        {
            root->left=create(root->left,x);
        }
        else
        {
            root->right=create(root->right,x);
        }
        return root;
    }
}
int first1[1010];
int first2[1010];
int cnt1=0;
int cnt2=0;
int last1[1010];
int last2[1010];
int top1=0;
int top2=0;
int a[1010];
void first1_root(tree*root)
{
    if(root)
    {

        first1[cnt1++]=root->data;
        first1_root(root->left);
        first1_root(root->right);
    }
}
void first2_root(tree*root)
{
    if(root)
    {

        first2[cnt2++]=root->data;
        first2_root(root->right);
        first2_root(root->left);
    }
}
void last1_root(tree*root)
{
    if(root)
    {

        last1_root(root->left);
        last1_root(root->right);
        last1[top1++]=root->data;
    }
}
void last2_root(tree*root)
{
    if(root)
    {

        last2_root(root->right);
        last2_root(root->left);
        last2[top2++]=root->data;
    }
}
int main()
{
    tree*root;
    root=NULL;
    int n;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        int x;
        scanf("%d",&x);
        root=create(root,x);
        a[i]=x;
    }
    int flag1=0;
    int flag2=0;
    first1_root(root);
    first2_root(root);
    for(int i=0; i<n; i++)
    {
        if(a[i]!=first1[i])
        {
            flag1=1;
        }
        if(a[i]!=first2[i])
        {
            flag2=1;
        }
    }
    last1_root(root);
    last2_root(root);
    if(flag1==1&&flag2==1)
    {
        printf("NO\n");
    }
    else
    {
        printf("YES\n");
        if(flag1==0)
        {
            for(int i=0; i<top1; i++)
            {
                if(i==top1-1)
                {
                    printf("%d\n",last1[i]);
                }
                else
                {
                    printf("%d ",last1[i]);
                }
            }
        }
        else if(flag2==0)
        {
            for(int i=0; i<top2; i++)
            {
                if(i==top2-1)
                {
                    printf("%d\n",last2[i]);
                }
                else 
                {
                    printf("%d ",last2[i]);
                }
            }
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值