1043. Is It a Binary Search Tree (25)

the problem is from pat,which website is http://pat.zju.edu.cn/contests/pat-a-practise/1043

and the source code is as followed.

#include<iostream>
#include<vector>
#include<cstdio>

using namespace std;
int pos;

struct cell
{
    cell *lchild;
    cell *rchild;
    int c;
    cell()
    {
        lchild = rchild = NULL;
    }
};

void insert1(cell *&root,int x)
{
    if (!root)
    {
        root = new cell;
        root->c = x;
    }
    else
    {
        if (x < root->c)
        {
            insert1(root->lchild,x);
        }
        else
            insert1(root->rchild,x);
    }
}
void insert2(cell *&root,int x)
{
    if (!root)
    {
        root = new cell;
        root->c = x;
    }
    else
        if (x > root->c)
        {
            insert2(root->lchild, x);
        }
        else
            insert2(root->rchild, x);
}
void preOrder(cell *root,vector<int> &v)
{
    v.push_back(root->c);
    if (root->lchild != NULL)
        preOrder(root->lchild,v);
    if (root->rchild != NULL)
        preOrder(root->rchild,v);
}

void postOrder(cell *root,vector<int> &v)
{
    if (root->lchild != NULL)
        postOrder(root->lchild, v);
    if (root->rchild != NULL)
        postOrder(root->rchild, v);
    v.push_back(root->c);
}


int main()
{
    int n;
    vector<int> v1,v2,v3,v;
    scanf("%d",&n);
    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d",&x);
        v1.push_back(x);
    }
    cell *r = NULL;//THE root of bst
    cell *r1 = NULL;//the root of mirror of bst;
    for (int i = 0; i < n; i++)
    {
        insert1(r,v1[i]);
        insert2(r1,v1[i]);
    }
    preOrder(r,v2);//the preorder of bst
    preOrder(r1,v3);//the preorder of the mirror of bst

    if (v2 != v1 && v3 != v1)
    {
        printf("NO
");
        return 0;
    }
    else
    {
        printf("YES
");
        if (v2 == v1)
        {
            postOrder(r,v);
            for (int i = 0; i < n; i++)
            {
                printf("%d%c",v[i], ((i - n + 1) ? ' ' : '
'));//this type of presentation is fitted for the pattern of pat.

            }
        }
        else if(v3 == v1)
        {
            postOrder(r1,v);
            for (int i = 0; i < n; i++)  
                printf("%d%c", v[i], ((i - n + 1) ? ' ' : '
'));
        }
    }
    return 0;
}

i think what is the most important for the bst-like problem is build a bst. that’s the point.

as long as the bst is built,then some trial things remains.

原文地址:https://www.cnblogs.com/maverick-fu/p/3967169.html