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

题目:输入一个整数组,判断该是不某二元查找树的后序遍历结果。
如果是返回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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值