1043. Is It a Binary Search Tree (25)

笨方法,勉强看一看吧

#define  _CRT_SECURE_NO_WARNINGS 

#include<string>
#include<string.h>
#include<vector>
#include<map>
#include<stack>
#include<iostream> 
#include<algorithm>
#include<stdio.h> 
using namespace std; 
struct Node
{
int num;
Node *left, *right;
Node()
{
left = right = NULL;
}
};
bool InsertNode(Node *seq_left, int i, int N)

Node *root = seq_left;
while (N--)
{
if (seq_left[i].num < root->num)
{
//插入树的左边
if (root->right != NULL)
return false;
if (root->left == NULL)
{
root->left = &seq_left[i];
return true;
}
else
{
root = root->left;
}
}
else//插入树的右边
{
if (root->right == NULL)
{
root->right = &seq_left[i];
return true;
}
else
{
root = root->right;
}
}
}
return false;
}
bool InsertNodeMirror(Node *seq_left, int i, int N)
{
Node *root = seq_left;
while (N--)
{
if (seq_left[i].num >= root->num)
{
//插入树的左边
if (root->right != NULL)
return false;
if (root->left == NULL)
{
root->left = &seq_left[i];
return true;
}
else
{
root = root->left;
}
}
else//插入树的右边
{
if (root->right == NULL)
{
root->right = &seq_left[i];
return true;
}
else
{
root = root->right;
}
}
}
return false;
}
void DisPlay(Node *seq,bool end=false)
{
if (seq->left != NULL)
DisPlay(seq->left);
if (seq->right != NULL)
DisPlay(seq->right);
if (end)
cout << seq->num;
else
cout << seq->num << " ";
}
int main()
{  
int N;
cin >> N;
int *number = new int[N]; 
for (int i = 0; i < N; i++)
{
scanf("%d", &number[i]); 
}
//查找树
Node *seq_left = new Node[N];
seq_left[0].num = number[0];
seq_left[0].left = seq_left[0].right = NULL;
bool tree = true;
for (int i = 1; i < N; i++)
{
seq_left[i].num = number[i];
if (!InsertNode(seq_left, i, N))
{
tree = false;
break;
}
}
if (!tree)
{
tree = true;
Node *seq_mirr = new Node[N];
seq_mirr[0].num = number[0];
seq_mirr[0].left = seq_mirr[0].right = NULL;
for (int i = 1; i < N; i++)
{
seq_mirr[i].num = number[i];
if (!InsertNodeMirror(seq_mirr, i, N))
{
tree = false;
break;
}
}
if (!tree)
{
cout << "NO\n";
}
else
{
cout << "YES\n";
DisPlay(seq_mirr,true);
}
}
else
{
cout << "YES\n";
DisPlay(seq_left,true);
}

return 0;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值