L2-004 这是二叉搜索树吗? (25 分)

题目链接
在这里插入图片描述
在这里插入图片描述
二叉树的基本操作,就是有点麻烦

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;

vector<int> s1;//记录非镜像前序
vector<int> s2;//记录镜像前序
int a[1010], n;

struct node {
    int data;
    struct node *left;
    struct node *right;
};

struct node *creat(struct node *root, int x) {  //非镜像建树
    if (root == NULL) {
        root = new node;
        root->data = x;
        root->left = NULL;
        root->right = NULL;
    } else {
        if (x < root->data)
            root->left = creat(root->left, x);
        else
            root->right = creat(root->right, x);
    }
    return root;
}

struct node *add(struct node *tree, int x) {  //镜像建树
    if (tree == NULL) {
        tree = new node;
        tree->data = x;
        tree->left = NULL;
        tree->right = NULL;
    } else {
        if (x >= tree->data)
            tree->left = add(tree->left, x);
        else
            tree->right = add(tree->right, x);
    }
    return tree;
}

void head(struct node *root) {  //非镜像前序
    if (root == NULL) return;
    s1.push_back(root->data);
    head(root->left);
    head(root->right);
    return;
}

void Front(struct node *tree) {  //镜像前序
    if (tree == NULL) return;
    s2.push_back(tree->data);
    Front(tree->left);
    Front(tree->right);
    return;
}

bool judge() {  //判断非镜像前序
    for (int i = 0; i < n; i++)
        if (s1[i] != a[i]) return false;
    return true;
}

bool check() {  //判断镜像前序
    for (int i = 0; i < n; i++)
        if (s2[i] != a[i]) return false;
    return true;
}

bool flag = 1;
void print(struct node *root) {  //后序输出
    if (root == NULL) return;
    print(root->left);
    print(root->right);
    if (flag)
        printf("%d", root->data);
    else
        printf(" %d", root->data);
    flag = 0;
    return;
}

int main(int argc, char const *argv[]) {
    cin >> n;
    struct node *root = NULL;  //非镜像
    struct node *tree = NULL;  //镜像
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        root = creat(root, a[i]);
        tree = add(tree, a[i]);
    }
    head(root);
    Front(tree);
    if (judge()) {
        printf("YES\n");
        print(root);
        printf("\n");
    } else if (check()) {
        printf("YES\n");
        print(tree);
        printf("\n");
    } else
        printf("NO\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值