题目:输入一个整数组,判断该是不某二元查找树的后序遍历结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历结果是这个列,因此返回false。
解法:树根即最后一个数值为中间值,root->left数值都小于root->data,root->right数值都大于root->data,如果是二叉查找树的话不存在相等的数值,而数组可以。故可以用递归调用左右子树,判断是否是后序遍历结果。
引用:
第9题:
其实,就是一个后序遍历二叉树的算法。
关键点:
1.//确定根结点
int root = squence[length - 1];
2.// the nodes in left sub-tree are less than the root
int i = 0;
for(; i < length - 1; ++ i)
{
if(squence[i] > root)
break;
}
// the nodes in the right sub-tree are greater than the root
int j = i;
for(; j < length - 1; ++ j)
{
if(squence[j] < root)
return false;
}
3.递归遍历,左右子树。
代码如下:
#include<stdio.h>
#include<stdlib.h>
bool VerifySquenceToBST(int squence[],int len)
{
if (squence==NULL||len<=0)
{
return false;
}
int root=squence[len-1];
int i=0;
for (; i<len-1; i++)
{
if (squence[i]>root)
{
break;
}
}
int j=i;
for (; j<len-1; j++)
{
if (squence[j]<root)
{
return false;
}
}
// verify whether the left sub-tree is a BST
bool left=true;
if (i>0)//if (i>=0)会出错,因为只有一个结点时,结果应为true,而只有一个结点,i=0;而left在递归时调用VerifySquenceToBST(squence,0),len==0,return false;
left=VerifySquenceToBST(squence,i);
// verify whether the right sub-tree is a BST
bool right=true;
if (j<len-1)
right=VerifySquenceToBST(squence+i,len-1-i);//len-2-i+1
return (left&&right);
}
int main()
{
int a[7]={5,7,6,9,11,10,8};
if(VerifySquenceToBST(a,7))
{
printf("True\n");
}
else
{
printf("False\n");
}
system("pause");
}
运行结果:
5,7,6,9,11,10,8
True
5,7,6,9,11,10,8 ,8(数组长度要变下)
True
7,4,6,5
False