您的位置:首页 > 其它

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

2015-05-31 17:06 344 查看
#include<iostream>

using namespace std;

/*

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

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

如果是返回true,否则返回false。

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

8

/ \

6  10

/ \ / \

5  7 9 11

因此返回true。

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

二叉树的问题都应该是递归问题

所以判断一个序列是不是二元查找树的后序排列

最主要的就是该序列的最后一个元素肯定是根节点

再根据根节点划分空间

左子树小于根节点

右子树大于根节点

再递归划分

*/

bool process(int data[],int low,int high){
if (low == high)  return 1;
int root = data[high],i,j,left=1,right=1;
for ( i = high - 1; i >= low && root <= data[i]; i--);
for (j = low; j < i; j++){
if (data[j] > root)    return 0;
}
right = process(data, i+1,high-1);
left  = process(data, low,i);
return left&&right;

}

int main(void)

{
int data[10],n;
bool result;
cout << "please input value numbers:";
cin >> n;
for (int i = 0; i < n; i++)
cin >> data[i];
result = process(data,0,n-1);
if (result)  cout << "it's a Binary searching tree" << endl;
else         cout << "It's not a Binary searching tree" << endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法