您的位置:首页 > 其它

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

2012-12-12 19:10 246 查看
题目:

判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
  8
  / /
  6 10
  / / / /
  5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。

答案:

//20121212
#include <iostream>
#include <vector>
using namespace std;

bool judgeTree(vector<int> const *n_vec);
int main()
{
vector<int> n_vector;
int i;
while (1)
{
cin>>i;
if (i==0)//最后的以0结束
{
break;
}
n_vector.push_back(i);
}
bool b=judgeTree(&n_vector);
cout<<b<<endl;
}
bool judge(vector<int> const *n_vec,int s,int e)
{
if (s<e)
{
int n=s;
while ((*n_vec)
<(*n_vec)[e])
{
n++;
}
for (int i=n;i<e;i++)
{
if ((*n_vec)[i]<(*n_vec)[e])
{
return false;
}
}
int b=judge(n_vec,s,n);
if (b)
{
if (judge(n_vec,n,e))
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}
}
else
{
return true;
}
}
bool judgeTree(vector<int> const *n_vec)
{
int n=n_vec->size();
bool b=judge(n_vec,0,n_vec->size()-1);
return b;
}


参考文章:http://www.cnblogs.com/aLittleBitCool/archive/2011/01/19/1939683.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  后序遍历