判断二叉搜索树的后序是否有效
Judge whether the post order of a binary search tree is valid
这是我的代码,有三个测试用例,但我只通过了其中的两个。我不知道代码有什么问题。请帮帮我!
#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。
相关文章:
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 钳制迭代器是否有效
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 模板签名解析为 void(void) 被 GCC 拒绝;这是否有效C++?
- 我如何知道作为参数的size_t在函数中是否有效?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 此递归模板类型定义是否有效C++?
- 将 C 函数转换为 C++ 以检查数字是否有效
- 函数参数的名称与调用函数时使用的变量相同是否有效?
- 如何检查输入是否有效?
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- 如何检查isupper(cstr)是否有效?
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 创建加密安全密码.并验证它是否有效