二叉搜索树的后序遍历序列
2017-07-23 10:52 tlnshuju 阅读(379) 评论(0) 编辑 收藏 举报题目:
输入一个整形数组。推断该数组是不是某二叉搜索树的后序遍历的结果.假设是则返回true,否则返回false. 假设输入的数组的随意两个数字都互不相同.
比如输入数组{5,7,6,9,11,10,8},则返回true.
{7,4,6,5}则返回false.
思路:
后序遍历最后一个结点是根结点. 从第一个结点開始。找第一个大于根结点的结点,则这个结点的左边是左子树。右边是右字数.推断右子树有没有小于根结点的结点,假设有则不符合二叉搜索树的特性.若没有,则递归推断左右子树.
bool VerifySquenceOfBST(int arr[], int length)
{
if (arr == NULL || length <= 0)
return false;
int root = *(arr+length-1);
int i = 0;
for (; i < length - 1; ++i)
{
if (arr[i] > root)
break;
}
int j = i;
for (; j < length - 1; ++j)
{
if (arr[j] < root)
return false;
}
bool left = true;
if (i > 0)
left = VerifySquenceOfBST(arr,i);
bool right = true;
if (i < length - 1)
right = VerifySquenceOfBST(arr + i, length - i - 1);
return left&&right;
}
//相同的方法,我们也能够得到前序遍历序列
bool VerifyPreOrderOfBST(int arr[], int length)
{
if (arr == NULL || length <= 0)
return false;
int root = arr[0];
int i = 1;
for (; i < length; ++i)
{
if (arr[i] > root)
break;
}
int j = i;
//日了*了。这里把for写成了fot,提示我括号和分号不正确,我找了10几分钟眼睛都快
//花了!!!
for (; j < length; ++j)
{
if (arr[j] < root)
return false;
}
bool left = true;
if (i > 1)
left = VerifyPreOrderOfBST(arr+1, i);
bool right = true;
if (i < length)
right = VerifyPreOrderOfBST(arr+i, length - i);
return left&&right;
}
void Test()
{
printf("Test postOrder:\n");
int arr[] = {5,7,6,9,11,10,8};
bool res1 = VerifySquenceOfBST(arr,7);
int arr1[] = {7,4,6,5};
bool res2 = VerifySquenceOfBST(arr1,7);
bool res3 = VerifySquenceOfBST(NULL,1);
printf("res1: %d\n",res1);
printf("res2: %d\n",res2);
printf("res3: %d\n",res3);
printf("Test PreOrder:\n");
int arr2[] = {8,6,5,7,10,9,11};
bool res4 = VerifyPreOrderOfBST(arr2,7);
int arr3[] = {8,6,5,10,9,7,11};
bool res5 = VerifyPreOrderOfBST(arr3,7);
printf("res4: %d\n",res4);
printf("res5: %d\n",res5);
}