输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
vector<int> leftSubTree;//存入左孩子
vector<int> rightSubTree;//存入右孩子
int root = 0; //存放根节点的值
int flag = 0;//根据flag的值决定结果存入右孩子还是左孩子
bool result = true;
if (sequence.empty()) return false;//如果sequence为空的时候返回false
root = *(sequence.end() - 1);
for (auto it = sequence.begin(); it != sequence.end()-1; it++) //划分左孩子和右孩子
{
if (*it < root&&flag == 0)
leftSubTree.push_back(*it);
else if (*it > root)
{
flag = 1;
rightSubTree.push_back(*it);
}
else
{
rightSubTree.push_back(*it);
}
}
//根据左孩子和右孩子判断结果,左孩子的所有值都小于根节点,右孩子的所有值都大于根节点
//这里左孩子不用判断,因为上述存储中已经保证
for (auto it = rightSubTree.begin(); it != rightSubTree.end(); ++it)
{
if (*it < root)
{
result = false;
break;
}
}
if (result == false) //第一次检查错误,不在递归,范围false
return false;
if (!rightSubTree.empty()&&!leftSubTree.empty()) //进行下次递归时要判断左子树和右子树是否为空,为空的时候不需要进行递归
result = VerifySquenceOfBST(rightSubTree)&&VerifySquenceOfBST(leftSubTree);
else if(!rightSubTree.empty() && leftSubTree.empty())
result = VerifySquenceOfBST(rightSubTree) ;
else if (rightSubTree.empty() && !leftSubTree.empty())
result = VerifySquenceOfBST(leftSubTree);
else
result = true;
return result;
}
};
int main()
{
Solution so;
vector<int> tree1 = { 5,7, 6, 9, 11, 10, 8 };
vector<int> tree2 = { 7,4,6,5 };
bool result1 = so.VerifySquenceOfBST(tree1);
cout << "tree1结果是:" ;
cout << result1 << endl;
cout << endl;
bool result2 = so.VerifySquenceOfBST(tree2);
cout << "tree2结果是:";
cout << result2 << endl;
cout << endl;
return 0;
}