您的位置:首页 > 其它

判断数组序列是否是二叉搜索树的后序遍历

2015-08-10 20:43 295 查看
#include <iostream>
using namespace std;

bool isPostorderOfBST(int postorder[], int low, int high)
{
if(postorder == NULL || low < 0 || high < 0) return false;

if(low == high) return true;

int pivot = high - 1; // 查找左子树与右子树的分界点
while(pivot >= 0 && postorder[pivot] > postorder[high])
{
--pivot;
}

int lowIndex = pivot;
while(lowIndex >= 0 && postorder[lowIndex] < postorder[high])
{
--lowIndex;
}

if(lowIndex >= 0) return false; // 左子树所有元素都比根节点要小

if(pivot + 1 < high && !isPostorderOfBST(postorder, pivot + 1, high - 1)) // 判断右子树
{
return false;
}

if(low <= pivot && !isPostorderOfBST(postorder, low, pivot)) // 判断左子树
{
return false;
}

return true;
}

int main(int argc, char const *argv[])
{
int postorder0[] = {5, 7, 6, 9, 11, 10, 8};
int postorder1[] = {11, 10, 9, 8, 7, 6, 5};
int postorder2[] = {5, 6, 7, 8, 9, 10, 11};
int postorder3[] = {8, 9, 5, 11, 10, 7, 6};
int postorder4[] = {7, 6, 12, 5, 11, 10, 9};
cout << "{5, 7, 6, 9, 11, 10, 8}---" << isPostorderOfBST(postorder0, 0, 6) << endl;
cout << "{11, 10, 9, 8, 7, 6, 5}---" << isPostorderOfBST(postorder1, 0, 6) << endl;
cout << "{5, 6, 7, 8, 9, 10, 11}---" << isPostorderOfBST(postorder2, 0, 6) << endl;
cout << "{8, 9, 5, 11, 10, 7, 6}---" << isPostorderOfBST(postorder3, 0, 6) << endl;
cout << "{7, 6, 12, 5, 11, 10, 9}---" << isPostorderOfBST(postorder4, 0, 6) << endl;

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