题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。 例
如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
分析:这是一道trilogy的笔试题,主要考查对二元查找树的理解。
在后续遍历得到的序列中,最后一个元素为树的根结点。从头开始扫描这个序列,比根结点小的元素都应该位于序列的
左半部分;从第一个大于跟结点开始到跟结点前面的一个元素为止,所有元素都应该大于跟结点,因为这部分元素对应
的是树的右子树。根据这样的划分,把序列划分为左右两部分,我们递归地确认序列的左、右两部分是不是都是二元查
找树。
//============================================================================
// Name : IfAfterTraverse.cpp
// Author : Lee
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
class LeeCom {
private:
int * datas;
int len;
public:
LeeCom() :
datas(NULL), len(0) {
}
LeeCom(int * a, int length) :
datas(a), len(length) {
}
bool judge(int * datas, int m, int n);
bool judge() {
return judge(datas, 0, len - 1);
}
virtual ~ LeeCom() {
}
};
bool LeeCom::judge(int * datas, int m, int n) {
if (m > n) {
return false;
} else if (m == n) {
return true;
} else {
int mid = datas[n];
int midpos;
for (midpos = m; midpos < n; midpos++) {
if (datas[midpos] > mid) {
break;
}
}
if (midpos > m) {
for (int j = m; j < midpos; j++) {
if (datas[j] > mid) {
return false;
}
}
}
if (midpos < n) {
for (int k = midpos; k <= n - 1; k++) {
if (datas[k] < mid)
return false;
}
}
bool left = true;
if (midpos > m) {
left = judge(datas, m, midpos - 1);
}
bool right = true;
if (midpos < n) {
right = judge(datas, midpos, n - 1);
}
return left && right;
}
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!
int a[7] = { 5, 7, 6, 8, 2, 10, 9 };
LeeCom lee(a, 7);
if (lee.judge() == true) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}