1043. Is It a Binary Search Tree (25)--BST引用插入、二叉树遍历模板

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>

#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>

using namespace std;

int N;
vector<int> v1,vpre,vmir;

struct node
{
    int data;
    node* l;
    node* r;
};

void insertt(int x,node* &p)//BST插入用引用
{
    if(p==NULL)
    {
        p=(node*)malloc(sizeof(node));
        p->data=x;
        p->l=NULL;
        p->r=NULL;
        return;
    }

    if(x < p->data)
    {
        insertt(x,p->l);
    }
    else if(x >= p->data)
    {
        insertt(x,p->r);
    }
}
void pre(node* p)//二叉树遍历模板
{
    if(p!=NULL)
    {
        vpre.push_back(p->data);
        pre(p->l);

        pre(p->r);
    }

}

void mir(node* p)
{
    if(p!=NULL)
    {
        vmir.push_back(p->data);
        mir(p->r);
        mir(p->l);
    }
}

bool judge1()
{
    for(int i=0;i<N;i++)
    {
        if(v1[i]!=vpre[i])
            return 0;
    }

    return 1;
}

bool judge2()
{
    for(int i=0;i<N;i++)
    {
        if(v1[i]!=vmir[i])
            return 0;
    }

    return 1;
}

int flag=0;
void tra(node* p)
{
    if(p!=NULL)
    {
        tra(p->l);
        tra(p->r);

        if(flag==1)
        {
            printf(" ");
            printf("%d",p->data);
        }
        else
        {
            flag=1;
            printf("%d",p->data);
        }
    }
}

void tra2(node* p)
{
    if(p!=NULL)
    {
        tra2(p->r);
        tra2(p->l);

        if(flag==1)
        {
            printf(" ");
            printf("%d",p->data);
        }
        else
        {
            flag=1;
            printf("%d",p->data);
        }
    }
}

int main()
{
   // freopen("in.txt","r",stdin);

    scanf("%d",&N);
    node* head=NULL;
    for(int i=0;i<N;i++)
    {
        int t;
        scanf("%d",&t);
        v1.push_back(t);
        insertt(t,head);
    }

    pre(head);
    mir(head);

    if(judge1()==1)
    {
        printf("YES\n");
        tra(head);
    }
    else if(judge2()==1)
    {
        printf("YES\n");
        tra2(head);
    }
    else
    {
        printf("NO");
    }



    return 0;
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值