【试题描述】输入一个整数数组,判断该数组是不是某二叉排序树的后序遍历结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字互不相同。
【试题来源】未知
【参考代码】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <iostream> using namespace std;
bool verifySquenceOfBST(int sequence[], int length) {
if(sequence == NULL || length <= 0) { return false; }
int root = sequence[length - 1];
int i = 0; while(i < length - 1) { if(sequence[i] > root) { break; } i++; }
int j = i; while(j < length - 1) { if(sequence[j] < root) { return false; } j++; }
bool left = true; if(i > 0) { left = verifySquenceOfBST(sequence, i); }
bool right = true; if(i > 0) { right = verifySquenceOfBST(sequence + i, length - i - 1); }
return left && right; }
int main() { int seq[] = {5, 7, 6, 9, 11, 10, 8}; int length = 7;
if(verifySquenceOfBST(seq, length)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }
|