【100题】判断一个序列是不是一个BST的后序遍历
2012-07-18 17:57
447 查看
//验证一个序列,是不是某个二叉查找树的后续遍历 #include <iostream> using namespace std; bool IsBST(int squence[], int length) { if(squence == NULL || length <= 0) { return false; } //最后一个值是根节点 int root = squence[length - 1]; //前一半是root的左子树,应该都小于root int i=0; for(;i < length-1; ++i) { if(squence[i] > root) { //一旦遇到大的,直接跳出循环,进入到右子树去 break; } } //后半部分是root的右子树,应该都大于root int j = i; for(;j<length-1;++j) { if(squence[j] < root) { //一旦遇到小的,直接返回,说明不是BST return false; } } //左边的信号量,先置为true bool left = true; if(i > 0) { //递归调用左边的,看看是不是BST left = IsBST(squence,i); } //右边的信号量,先置为true bool right = true; if(i < length-1) { //递归调用右边的,看看是不是BST right = IsBST(squence+i,length-i-1); } //两边都是BST,则就是BST!! return (left&&right); } void main() { int BST[] = {1,7,5,12,18,15,10}; IsBST(BST,sizeof(BST)/sizeof(BST[0])) ? cout << "BST"<<endl : cout << "not BST"<<endl; }
相关文章推荐
- 程序员面试题100题第6题——判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试100题之六,判断整数序列是不是二元查找树的后序遍历结果
- 二叉搜索树的后序遍历序列输入一个整数数组,判断该数组是不是二叉搜索树的后序遍历序列
- 判断给出的序列是不是一个二叉搜索树的后序遍历
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 判断一个数组是不是二叉搜索树的后序遍历序列——剑指offer
- IT公司100题-9-判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 100题_06 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二叉查找树(BST)的后序遍历结果
- 判断一个序列是不是二叉搜索树的后序遍历序列
- 面试100题:9.判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 程序员面试题精选100题(06)-判断整数序列是不是二元查找树的后序遍历结果
- 剑指offer-第四章解决面试题思路(判断一个数组是否为二叉搜索树的后序遍历序列)
- 剑指offer——判断一个序列是否为二叉搜索树的后序遍历
- 【100题】给定入栈序列,判断一个序列是否可能为输出序列
- 判断一个数组序列为二叉树的后序遍历序列
- 微软算法100题09 判断整数序列是不是二元查找树的后序遍历结果