判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是二元查找树的后序遍历结果,如果是,返回true,否则返回假,具体实现如下:
#include <iostream> using namespace std; //搜索树后序遍历数组最后一个是根,从数组头到第一个比根大的节点是左孩子,后面右孩子必须全大于根,递推 static bool VerifyArrayOfBST(int a[], int start, int length) { if (a[length]<a[start]) { return false; } if (length == 0) { for (int i = 0; i <= length; i++) { if (a[i + start]>a[length + start]) { if (i>0) { VerifyArrayOfBST(a, start, i); } if (length - i>0) { VerifyArrayOfBST(a, start + i, length - i); } } } } return true; } int main(int argc, char * argv[]) { int a[] = { 1, 6, 4, 3, 5 }; int a1[] = { 7, 6, 4, 3, 5 }; VerifyArrayOfBST(a, 0, 4); VerifyArrayOfBST(a1, 0, 4); if (VerifyArrayOfBST(a, 0, 4) == true) { cout << "a是搜索树" << endl; } else{ cout << "a不是搜索树" << endl; } if (VerifyArrayOfBST(a1, 0, 4) == true) { cout << "a1是搜索树" << endl; } else{ cout << "a1不是搜索树" << endl; } system("pause"); return 0; }运行效果如图1所示:
图1 运行效果