判断数组序列是否是二叉搜索树的后序遍历
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; }
相关文章推荐
- php往XML中写入中文出现乱码的解决方案
- KM算法(二分图的最佳完美匹配)
- 今日你总结
- JS判断字符串是否包含中文
- ZOJ 3212 K-Nice
- foreach
- 高性能网络编程1----accept建立连接
- ZOJ 3211 Dream City
- Android安全机制
- ACM最大子串和问题
- C 和 OC 字符串转换 NSString 和 char * 转换 const char* 与 char *
- mysql数据库基本语法与操作
- 通过经纬度坐标计算两个点之间的距离
- NYOJ 860 又见01背包
- leetcode 96: Unique Binary Search Trees
- 序列化必须所有子类都要实现序列化
- php读写XML文件
- 如何让Qt应用程序只有一个实例
- HDU 2178.猜数字【分析能力练习】【读题能力练习】【8月10】
- UICollectionView的使用