您的位置:首页 > 其它

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

2018-03-09 00:45 459 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: