判断二叉搜索树的后序是否有效

Judge whether the post order of a binary search tree is valid

本文关键字:是否 有效 搜索树 判断      更新时间:2023-10-16

这是我的代码,有三个测试用例,但我只通过了其中的两个。我不知道代码有什么问题。请帮帮我!

#include <cstdio>
int isValid(int a[], int low, int high) {
    if (low >= high)
        return 1;
    int root = a[high];
    int i = 0;
    while (a[i] < root && i < high)
        i++;
    // i == low, the left child is null
    // i == high, the right child is null
    if (a[i - 1] < root && root < a[high - 1] 
        || i == low && root < a[high - 1] || a[i - 1] < root && i == high) {
        return isValid(a, low, i - 1) && isValid(a, i, high - 1);
    } else {
        return 0;
    }
}
int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        int a[n];
        for (int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        if (isValid(a, 0, n - 1)) {
            printf("Yesn");
        } else {
            printf("Non");     
        }
    }
    return 0;
}
样本输入:

7
5 7 6 9 11 10 8
4
7 4 6 5
样本输出:

Yes
No

Inorder可以保证BST的非递减顺序,但post -order不能。你不能从后序序列推导出原始二叉树。例如,5,7,6可能是有效的完整BST也可能是无效的BST。