#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; }
时间: 2024-10-15 09:19:29