判断整数序列是不是二元查找树的后序遍历结果

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回 true,否则返回 false。
例如输入 5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/
6 10
/ /
5 7 9 11
因此返回 true。
如果输入 7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回 false。
代码思路:
后序遍历为左右根。以5、7、6、9、11、10、8为例。8为根,然后找出5、7、6为左子树,9、11、10为右子树。然后进行分别递归。
代码(C++实现),本来用数组可以更容易完成,以下代码是为了复习c++中vector的操作。
采用三种数据
#include
#include
bool judge(std::vector a,int start,int end)
{
if (start < end)
{
int left = start;
while (a[left] < a[end])
{
left++;
}
int right = left;
while (right < end)
{
if (a[right] < a[end])
{
return 0;
}
right++;
}
judge(a, 0, left-1);
judge(a, left,end-1);
}
return 1;
}
void main()
{
std::vector a;
std::cout << "请输入后序遍历的数字个数" << std::endl;
int num = 0;
std::cin >> num;
for (int i = 0; i < num; i++)
{
int tmp;
std::cout << "请输入数字" << std::endl;
std::cin >> tmp;
a.push_back(tmp);
}
std::vector::iterator it;
for (it = a.begin(); it != a.end(); it++)
{
std::cout << *it << "  ";
}
if (judge(a,0,num-1)==1)
{
std::cout << "TRUE" << std::endl;
}
else
{
std::cout << "FALSE" << std::endl;
}
system(“pause”);
}