题目描述:
输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
思路:二元查找树,后序遍历的结果,最后一个数为树根节点root,前面可分为两部分,一部分比root小为左子树,
一部分比root大为右子树,此为正确的后序遍历的结果的特点。
所以本题的解题入口也就是这个特点:找到序列的root和左右子树,递归判断左右子树是否符合该特点。
需对递归算法有一定的掌握,值得学习研究。
bool IsPostOrder(const int a[], int len)
{
if (a == NULL || len <= 0)
return false;
//the root of bstree
int root = a[len - 1];
//left child tree of root
int i = 0;
for (; i < len - 1; i++)
{
if (a[i] >= root)
break;
}
//right child tree of root
int j = i;
for (; j < len - 1; j++)
{
if (a[j] <= root)
return false;
}
//check if the left child tree is postorder
bool bLeft = true;
if (i > 0)
{
bLeft = IsPostOrder(a, i);
}
//check if the right child tree is postorder
bool bRight = true;
if (i < len - 1)
{
bRight = IsPostOrder(a + i, len - i - 1);
}
//return result
return (bLeft && bRight);
}
int main()
{
int a[] = {2, 1, 4, 3, 7, 6, 9, 10, 8};
//int array[]={2, 2, 4, 3, 7, 6, 9, 10, 8};
bool flag = IsPostOrder(a, sizeof(a) / sizeof(*a));
if (flag)
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}