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

题目描述:

一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,

  • 其左子树中所有结点的键值小于该结点的键值;
  • 其右子树中所有结点的键值大于等于该结点的键值;
  • 其左右子树都是二叉搜索树。

所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。

输入格式:

输入的第一行给出正整数 N(≤1000)。随后一行给出 N 个整数键值,其间以空格分隔。

输出格式:

如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES ,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO

输入样例 1:

7
8 6 5 7 10 8 11

输出样例 1:

YES
5 7 6 8 11 10 8

输入样例 2:

7
8 10 11 8 6 7 5

输出样例 2:

YES
11 8 10 7 5 6 8

输入样例 3:

7
8 6 8 5 10 9 11

输出样例 3:

NO
#include <iostream>
#include <algorithm>

using namespace std;

// 判断前序
bool isPre(int *a, int left, int right){
    if (left >= right)
        return true;
    int i = left+1, j; // 根
    while (i<=right && a[i]<a[left]) // 左子树小于根
        i++;
    j = i;
    while (i<=right && a[i]>=a[left]) // 右子树大于等于根
        i++;
    if (i <= right)
        return false;
    bool m = isPre(a, left+1, j-1); // 递归左子树
    bool n = isPre(a, j, right); // 递归右子树
    return n&&m;
}

// 判断镜像
bool isMirror(int* a, int left, int right){
    if (left >= right)
        return true;
    int i = left+1, j;
    while (i<=right && a[i]>=a[left])
        i++;
    j = i;
    while (i<=right && a[i]<a[left])
        i++;
    if (i <= right)
        return false;
    bool m = isMirror(a, left+1, j-1);
    bool n = isMirror(a, j, right);
    return m&&n;
}

// 构造后序
void preInToPost(int len, int* pre, int* in, int* post){
    if (len <= 0)
        return ;
    int p, i;
    for (i = 0; i < len; i++)
        if (pre[0] == in[i]){
            p = i;
            break;
        }
    preInToPost(p, pre+1, in, post);
    preInToPost(len-p-1, pre+p+1, in+p+1, post+p);
    post[len-1] = pre[0];
}

// 镜像构造后序
void preInToPost_Mirror(int len, int* pre, int* in, int* post){
    if (len <= 0)
        return ;
    int p, i;
    for (i = len-1; i >= 0; i--)
        if (pre[0] == in[i]){
            p = i;
            break;
        }
    preInToPost(p, pre+1, in, post);
    preInToPost(len-p-1, pre+p+1, in+p+1, post+p);
    post[len-1] = pre[0];
}

bool cmp(int a, int b){
    return a > b;
}

int pre[1005], in[1005], post[1005];

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        cin >> pre[i];
        in[i] = pre[i];
    }
    
    if (isPre(pre, 0, n-1)){ // 二叉搜索树
        cout << "YES" << endl;
        sort(in, in+n);
        preInToPost(n, pre, in, post);
        cout << post[0];
        for (int i = 1; i < n; i++)
            cout << " " << post[i];
    }
    else if (isMirror(pre, 0, n-1)){ // 镜像
        cout << "YES" << endl;
        sort(in, in+n, cmp);
        preInToPost_Mirror(n, pre, in, post);
        cout << post[0];
        for (int i = 1; i < n; i++)
            cout << " " << post[i];
    } else
        cout << "NO";
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章