2021-04-04 PAT A1073

一开始没有注意到不管怎么插入,最后都是插入成正确的BST,结果还以为会插成镜像的BST,导致交换a b的时候出错了,这里感觉可能算法慢了,因为要正确的BST和镜像的都检查一遍

#include
using namespace std;
int input[1010];
struct node {
    node(int n) { data = n; child[0] = NULL, child[1] = NULL; }
    int data;
    node* child[2];
};
int a = 0, b = 1;//用来指导镜像

bool preorder(node* root, int& index, bool& cmp) {
    if (!cmp)return false;
    if (root != NULL) {
        if (root->data != input[index++]) cmp = false;
        preorder(root->child[a], index, cmp);
        preorder(root->child[b], index, cmp);
    }
    return cmp;
}

void insert(node* &root, int par) {//给二叉查找树插入节点
    if (root == NULL) {
        root = new node(par); return; 
    }
    if (par < root->data) insert(root->child[0], par);
    else insert(root->child[1], par);
}

void postorder(node* root, bool& cmp) {
    if (root != NULL) {
        postorder(root->child[a], cmp);
        postorder(root->child[b], cmp);
        if (cmp) {
            cmp = false;
            printf("%d", root->data);
        }
        else printf(" %d", root->data);
    }
}
int main() {
    int n, index = 0; scanf("%d", &n);
    node* root = NULL; bool jud = true;
    for (int i = 0; i < n; i++) {
        scanf("%d", &input[i]);
        insert(root, input[i]);
    }
    if(preorder(root,index,jud));
    else{
        jud = true;index = 0;
        a = 1,b = 0;
        preorder(root,index,jud);
    }
    if (jud) {
        printf("YES\n");
        jud = true;
        postorder(root, jud);
    }
    else printf("NO");
}

你可能感兴趣的:(2021-04-04 PAT A1073)