您的位置:首页 > 其它

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

2013-05-09 13:30 316 查看
第9题

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

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。

如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8

/ \

6 10

/ \ / \

5 7 9 11

因此返回true。

如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

/*
Name:
Copyright:
Author:
Date: 22-06-11 10:52
Description: 判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的中序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6  10
/\  /\
5 7 9 11
因此返回true。
采用递归;
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
*/
#include<iostream>
#include<iomanip>
using namespace std;

bool cfun(int a[],int p,int r)
//a 为数组,假设下标从零开始
{
bool ret=false;
const int len=r-p+1;
if(p==r)
{
return true;
}
else
{
bool b;
for(int i=p;i<=r;++i)
{
b=true;
for(int j=i+1;j<=r;++j)
{
if(a[j]<a[i])
{
b=false;
break;
}
}
if(b)
{
for(int j=p;j<i;++j)
{
if(a[j]>a[i])
{
b=false;
break;
}
}
}
if(b)
{
if(i==p)
ret=cfun(a,i+1,r);
else
{
if(i==r)
ret=cfun(a,p,i-1);
else
ret=cfun(a,p,i-1)&&cfun(a,i+1,r);
}
if(ret)
return true;
}

}
return false;
}
}

int main()
{
int a[]={7,4,6,5};
bool b=cfun(a,0,3);
if(b)
cout<<"true";
else
cout<<"false";
cout<<endl;
system("pause");
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐