// 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;
}
