题目:
这题的单调栈做法十分不好想,因为要有十足的观察力才行。
这里我使用的是一般通解,即递归法:
对每一个区间都去找到左右子树的分割节点,然后判断是否所有右子树(因为左子树元素在划分时能保证都小于当前遍历时的根节点)元素都满足这个条件。如果满足,就继续递归。
C++(附带测试,二叉搜索树请使用数组创建)
#include<iostream>
#include<vector>
#include<set>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val):val(val),left(nullptr),right(nullptr){}
};
TreeNode* insert(TreeNode* root,int val){
if(root==nullptr){
root = new TreeNode(val);
return root;
}
else if(val<root->val){
root->left = insert(root->left,val);
}
else if(val>root->val){
root->right = insert(root->right,val);
}
return root;
}
TreeNode* createTree(vector<int> a){
TreeNode* root = new TreeNode(a[0]);
for(int i=1;i<a.size();i++){
root = insert(root,a[i]);
}
return root;
}
void inorder(TreeNode* root){
if(root==nullptr){
return;
}
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
return recur(postorder,0,postorder.size()-1);
}
bool recur(vector<int>& postorder,int left,int right){
if(left>=right){
return true;
}
int i = left;
while(postorder[i]<postorder[right]){
i++;
}
int j = i-1;
while(postorder[i]>postorder[right]){
i++;
}
if(i<right){
return false;
}
return recur(postorder,left,j)&&recur(postorder,j+1,right-1);
}
};
class Solution {
public:
bool digui(int front,int tail,vector<int>& postorder){
if(front >= tail) return true;
int index=front;
while(postorder[index] < postorder[tail]){
index++;
}
int leftTail = index-1;
while(postorder[index] > postorder[tail]){
index++;
}
if(index < tail) return false;
return digui(front,leftTail,postorder) && digui(leftTail+1,tail-1,postorder);
}
bool verifyPostorder(vector<int>& postorder) {
return digui(0,postorder.size()-1,postorder);
}
};
int main(){
vector<int> a = {5,6,2,3,1};
TreeNode* root = createTree(a);
inorder(root);
}